std::abs(int), std::labs, std::llabs, std::imaxabs

From cppreference.com
< cpp‎ | numeric‎ | math
 
 
 
Common mathematical functions
Functions
Basic operations
abs(int)labsllabsimaxabs
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)(C++11)(C++11)
Exponential functions
(C++11)
(C++11)
(C++11)
(C++11)
Power functions
(C++11)
(C++11)
Trigonometric and hyperbolic functions
(C++11)
(C++11)
(C++11)
Error and gamma functions
(C++11)
(C++11)
(C++11)
(C++11)
Nearest integer floating point operations
(C++11)(C++11)(C++11)
(C++11)
(C++11)
(C++11)(C++11)(C++11)
Floating point manipulation functions
(C++11)(C++11)
(C++11)
(C++11)
(C++11)(C++11)
(C++11)
Classification/Comparison
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
Macro constants
(C++11)(C++11)(C++11)(C++11)(C++11)
 
Defined in header <cstdlib>
Defined in header <cmath>
(since C++17)
int       abs( int n );
long      abs( long n );
long long abs( long long n );
(since C++11)
Defined in header <cstdlib>
long       labs( long n );
long long llabs( long long n );
(since C++11)
Defined in header <cinttypes>
(since C++11)
(since C++11)

Computes the absolute value of an integer number. The behavior is undefined if the result cannot be represented by the return type.

Parameters

n - integer value

Return value

The absolute value of n (i.e. |n|), if it is representable.

Notes

In 2's complement systems, the absolute value of the most-negative value is out of range, e.g. for 32-bit 2's complement type int, INT_MIN is -2147483648, but the would-be result 2147483648 is greater than INT_MAX, which is 2147483647.

Example

#include <iostream>
#include <cstdlib>
#include <climits>
 
int main()
{
    std::cout << "abs(+3) = " << std::abs(3) << '\n'
              << "abs(-3) = " << std::abs(-3) << '\n';
 
//  std::cout << abs(INT_MIN)); // undefined behavior on 2's complement systems
}

Output:

abs(+3) = 3
abs(-3) = 3

See also

absolute value of a floating point value (|x|)
(function)
returns the magnitude of a complex number
(function template)
applies the function std::abs to each element of valarray
(function template)
C documentation for abs, labs, llabs