Standards / Extensions | C or C++ | Dependencies |
---|---|---|
ISO C |
both |
#include <stdlib.h>
int abs(int n);
long abs(long n); /* C++ only */
#include <math.h>
double abs(double n); /* C++ only */
float abs(float n); /* C++ only */
long double abs(long double n); /* C++ only */
float absf(float n);
long double absl(long double n);
#define __STDC_WANT_DEC_FP__
#include <math.h>
_Decimal32 abs(_Decimal32 x); /* C++ only */
_Decimal64 abs(_Decimal64 x); /* C++ only */
_Decimal128 abs(_Decimal128 x); /* C++ only */
#define _TR1_C99
#include <inttypes.h>
intmax_t abs(intmax_t n);
#define _TR1_C99
#include <stdlib.h>
long long abs(long long n);
The functions abs(), absf(), and absl() return the absolute value of an argument n.
For the integer version of abs(), the minimum allowable integer is INT_MIN+1. (INT_MIN is a macro that is defined in the limits.h header file.) For example, with the z/OS® XL C/C++ compiler, INT_MIN+1 is -2147483648.
For the double, float, and long double versions of abs(), the minimum allowable values are DBL_MIN+1, FLT_MIN+1, and LDBL_MIN+1, respectively. (The floating-point macro constants are defined in the float.h header file.)
If the value entered cannot be represented as an integer, the abs(), absf(), and absl() functions return the same value.
Special behavior for C++: For C++ applications, abs() is also overloaded for the types long, float, and long double.
The returned value is the absolute value, if the absolute value is possible to represent.
Otherwise the input value is returned.
There are no errno values defined.
⁄* CELEBA02
This example calculates the absolute value of an integer
x and assigns it to y.
*⁄
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int x = -4, y;
y = abs(x);
printf("The absolute value of %d is %d.\n", x, y);
}
The absolute value of -4 is 4.