std::abs, std::labs, std::llabs, std::imaxabs

Header: <cstdlib>

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

# Declarations

int abs( int num );

(constexpr since C++23)

long abs( long num );

(constexpr since C++23)

long long abs( long long num );

(since C++11) (constexpr since C++23)

long labs( long num );

(constexpr since C++23)

long long llabs( long long num );

(since C++11) (constexpr since C++23)

std::intmax_t abs( std::intmax_t num );

(since C++11) (constexpr since C++23)

std::intmax_t imaxabs( std::intmax_t num );

(since C++11) (constexpr since C++23)

# Parameters

# Return value

The absolute value of num (i.e. |num|), 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 <climits>
#include <cstdlib>
#include <iostream>
 
int main()
{
    std::cout << std::showpos
              << "abs(+3) = " << std::abs(3) << '\n'
              << "abs(-3) = " << std::abs(-3) << '\n';
 
//  std::cout << std::abs(INT_MIN); // undefined behavior on 2's complement systems
}

# Defect reports

DRApplied toBehavior as publishedCorrect behavior
LWG 2192C++98overloads of std::abs wereinconsistently declared in two headersdeclared these overloadsin both headers

# See also