C++ abs()

C++ abs(x) returns absolute value of the argument x.

Syntax

The syntax of C++ abs() is

abs(x)

where

ParameterDescription
xA double, float, long double, or integral type value.

Returns

The return value depends on the type of value passed for parameter x.

The return value of abs() is

  • double if x is double or integral type.
  • float if x is float.
  • long double if x is long double.

The synopsis of abs() function is

double abs(double x);
float abs(float x);
long double abs(long double x);
double abs(T x); // for integral type argument value

abs() is a function of cmath library. Include cmath library at the start of program, if using abs() function.

Example

In this example, we read a value from user into variable x, and find the absolute value of x using abs() function.

C++ Program

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

int main() {
    double x;
    cout << "Enter x : ";
    cin >> x;

    double result = abs(x);
    cout << "abs(" << x << ") : " << result << endl;
}

Output

Enter x : -5
abs(-5) : 5
Program ended with exit code: 0
Enter x : -inf
abs(-inf) : inf
Program ended with exit code: 0
Enter x : 22
abs(22) : 22
Program ended with exit code: 0

Conclusion

In this C++ Tutorial, we learned the syntax of C++ abs(), and how to use this function to find the absolute value of given argument, with the help of examples.