Abs
Defined in headers <cstdlib>
, <cinttypes>
, <cmath>
.
Description
Computes the absolute value of an integer number. The behavior is undefined if the result cannot be represented by the return type.
Declarations
- C++23
- C++11
- C++98
// 1)
int abs (int n);
// 2)
long int abs (long int n);
// 3)
constexpr long long int abs (long long int n);
// 4)
constexpr long labs( long n );
// 5)
constexpr long long llabs( long long n );
// 6)
constexpr /* floating-point-type */
abs( /* floating-point-type */ n );
// 7)
constexpr /* floating-point-type */
fabs ( /* floating-point-type */ n );
// 8)
constexpr float fabsf( float n );
// 9)
constexpr long double fabsl( long double n );
// 10)
std::intmax_t abs( std::intmax_t n );
// 11)
std::intmax_t imaxabs( std::intmax_t n );
// 16)
template< class Integer >
constexpr double fabs ( Integer n );
// 1)
int abs ( int n );
// 2)
long int abs ( long int n );
// 3)
long long int abs ( long long int n );
// 4)
long labs( long n );
// 5)
long long llabs( long long n );
// 6)
float abs( float n );
// 7)
double abs( double n );
// 8)
long double abs( long double n );
// 9)
float fabs ( float n );
// 10)
double fabs ( double n );
// 11)
long double fabs ( long double n );
// 12)
float fabsf( float n );
// 13)
long double fabsl( long double n );
// 14)
std::intmax_t abs( std::intmax_t n );
// 15)
std::intmax_t imaxabs( std::intmax_t n );
// 16)
template< class Integer >
double fabs ( Integer n );
// 1)
int abs (int n);
// 2)
long int abs (long int n);
// 3)
long labs( long n );
Parameters
n
- Integral value.
Return Value
The absolute value of n.
Examples
Here we find the absolute values of the negatives 5 and 2371041 using the abs function from cstdlib.
#include <iostream>
#include <cstdlib>
int main() {
std::cout << "Abs value of -5: "
<< abs(-5);
std::cout << "Abs value of -2371041: "
<< abs(-2371041);
return 0;
}
Abs value of -5: 5
Abs value of -2371041: 2371041
No-throw guarantee: this function throws no exceptions.
If the result cannot be represented by the returned type (such as abs(INT_MIN)
in an implementation with two's complement signed values), it causes undefined behavior.