Namespaces
Variants
Views
Actions

Difference between revisions of "cpp/numeric/math/abs"

From cppreference.com
< cpp‎ | numeric‎ | math
(Apply LWG2192 to C++98. [cinttypes.syn]/(1.2))
m
Line 34: Line 34:
  
 
{{rrev|since=c++11|
 
{{rrev|since=c++11|
Overloads for {{tt|std::intmax_t}} is provided in {{tt|<cinttypes>}} if and only if {{tt|std::intmax_t}} is an extended integer type.
+
Overload of {{tt|std::abs}} for {{tt|std::intmax_t}} is provided in {{tt|<cinttypes>}} if and only if {{tt|std::intmax_t}} is an extended integer type.
 
}}
 
}}
  

Revision as of 22:52, 5 November 2020

 
 
 
 
Defined in header <cstdlib>
Defined in header <cmath>
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.

If std::abs is called with an argument of arithmetic type X such that X(0) < X(-1) is true and X cannot be converted to int by integral promotion, the program is ill-formed.

Overload of std::abs for std::intmax_t is provided in <cinttypes> if and only if std::intmax_t is an extended integer type.

(since C++11)

Contents

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 << std::abs(INT_MIN); // undefined behavior on 2's complement systems
}

Output:

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

Defect reports

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

DR Applied to Behavior as published Correct behavior
LWG 2192 C++98 overloads of std::abs were separated in two headers declared these overloads in both headers

See also

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