C++ cstdlib abs()

The abs() function in C++ returns the absolute value of an integer number. This function is defined in the cstdlib header file.

Mathematically, abs(num) = |num|.

Example

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

int main() {

// get absolute value of -5 cout << abs(-5);
return 0; } // Output: 5

abs() Syntax

The syntax of the abs() function is:

abs(int num);

abs() Parameters

The abs() function takes the following parameters:

  • num: An integral value whose absolute value is returned. The number can be:
    • int
    • long
    • long long

abs() Return Value

The abs() function returns:

  • the absolute value of num i.e. |num|
  • the positive value if the specified number is negative

abs() Prototypes

The prototypes of abs() as defined in the cstdlib header file are:

int abs(int num);

long abs(long num);

long long abs(long long num);

abs() Overloading

The abs() function is also overloaded in:


Example: C++ abs()

#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; return 0; }

Output

abs(-5) = |-5| = 5
abs(-2371041) = |-2371041| = 2371041
Did you find this article helpful?

Your builder path starts here. Builders don't just know how to code, they create solutions that matter.

Escape tutorial hell and ship real projects.

Try Programiz PRO
  • Real-World Projects
  • On-Demand Learning
  • AI Mentor
  • Builder Community