C++ abs()

The abs() function in C++ returns the absolute value of an integer number.

This function is defined in <cstdlib> header file.

[Mathematics] |x| = abs(x) [C++ Programming]

The abs() function is also overloaded in header <cmath> for floating-point types, in header <complex> for complex numbers, and in header <valarray> for valarrays.


abs() prototype [As of C++ 11 standard]

int abs(int x);
long abs(long x);
long long abs(long long x);

The abs() function takes a single argument and returns a value of type int, long int or long long int.


abs() Parameters

x: An integral value whose absolute value is returned.

abs() Return value

The abs() function returns the absolute value of x i.e. |x|.


Example: How abs() function works in C++?

#include <iostream>
#include <cstdlib>
using namespace std;

int main()
{
	int x = -5;
	long y = -2371041;

	int a = abs(x);
	long b = abs(y);

	cout << "abs(" << x << ") = |" << x << "| = " << a << endl;
	cout << "abs(" << y << ") = |" << y << "| = " << b << endl;
}

When you run the program, the output will be:

abs(-5) = |-5| = 5
abs(-2371041) = |-2371041| = 2371041