abs, _abs64
Calculates the absolute value.
int abs(
int n
);
long abs(
long n
); // C++ only
long long abs(
long long n
); // C++ only
double abs(
double n
); // C++ only
long double abs(
long double n
); // C++ only
float abs(
float n
); // C++ only
__int64 _abs64(
__int64 n
);
Parameters
- n
Integer value.
Return Value
The abs function returns the absolute value of its parameter. There is no error return.
Remarks
Because C++ allows overloading, you can call overloads of abs that take and return long, long long, float, double, and long double values. In a C program, abs always takes and returns an int.
Microsoft Specific
Because the range of negative integers that can be represented by using any integral type is larger than the range of positive integers that can be represented by using that type, it's possible to supply an argument to abs that can’t be converted. If the absolute value of the argument cannot be represented by the return type, the abs functions return the argument value unchanged. Specifically, abs(INT_MIN) returns INT_MIN, labs(LONG_MIN) returns LONG_MIN, llabs(LLONG_MIN) returns LLONG_MIN, and _abs64(_I64_MIN) returns _I64_MIN. This means that the abs functions cannot be used to guarantee a positive value.
End Microsoft Specific
Requirements
Routine |
Required header |
---|---|
abs |
<math.h> |
_abs64 |
<stdlib.h> |
Example
This program computes and displays the absolute values of several numbers.
// crt_abs.c
// Build: cl /W3 /TC crt_abs.c
// This program demonstrates the use of the abs function
// by computing and displaying the absolute values of
// several numbers.
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <limits.h>
int main( void )
{
int ix = -4;
long lx = -41567L;
long long llx = -9876543210LL;
__int64 wx = -1;
// absolute 32 bit integer value
printf_s("The absolute value of %d is %d\n", ix, abs(ix));
// absolute long integer value
printf_s("The absolute value of %ld is %ld\n", lx, labs(lx));
// absolute long long integer value
printf_s("The absolute value of %lld is %lld\n", llx, llabs(llx));
// absolute 64 bit integer value
printf_s("The absolute value of 0x%.16I64x is 0x%.16I64x\n", wx,
_abs64(wx));
// Integer error cases:
printf_s("Microsoft implementation-specific results:\n");
printf_s(" abs(INT_MIN) returns %d\n", abs(INT_MIN));
printf_s(" labs(LONG_MIN) returns %ld\n", labs(LONG_MIN));
printf_s(" llabs(LLONG_MIN) returns %lld\n", llabs(LLONG_MIN));
printf_s(" _abs64(_I64_MIN) returns 0x%.16I64x\n", _abs64(_I64_MIN));
}
The absolute value of -4 is 4 The absolute value of -41567 is 41567 The absolute value of -9876543210 is 9876543210 The absolute value of 0xffffffffffffffff is 0x0000000000000001 Microsoft implementation-specific results: abs(INT_MIN) returns -2147483648 labs(LONG_MIN) returns -2147483648 llabs(LLONG_MIN) returns -9223372036854775808 _abs64(_I64_MIN) returns 0x8000000000000000