In the cstdlib library of C++, there are different functions for getting the absolute value except from abs. The abs are used basically for int type input in C, and int, long, long long in C++. The others are used for long, and long long type data etc. Let us see the usage of these functions.
The abs() Function
This function is used for int type data. So this returns the absolute value of the given argument. The syntax is like below.
int abs(int argument)
Example
#include <cstdlib> #include <iomanip> #include <iostream> using namespace std; main() { int x = -145; int y = 145; cout << "Absolute value of " << x << " is: " << abs(x) << endl; cout << "Absolute value of " << y << " is: " << abs(y) << endl; }
Output
Absolute value of -145 is: 145 Absolute value of 145 is: 145
The labs() Function
This function is used for long type of data. So this returns absolute value of the given argument. The syntax is like below.
long labs(long argument)
Example
#include <cstdlib> #include <iomanip> #include <iostream> using namespace std; main() { long x = -9256847L; long y = 9256847L; cout << "Absolute value of " << x << " is: " << labs(x) << endl; cout << "Absolute value of " << y << " is: " << labs(y) << endl; }
Output
Absolute value of -9256847 is: 9256847 Absolute value of 9256847 is: 9256847
The llabs() Function
This function is used for long long type data. So this returns the absolute value of the given argument. The syntax is like below.
long long labs(long long argument)
Example
#include <cstdlib> #include <iomanip> #include <iostream> using namespace std; main() { long long x = -99887654321LL; long long y = 99887654321LL; cout << "Absolute value of " << x << " is: " << llabs(x) << endl; cout << "Absolute value of " << y << " is: " << llabs(y) << endl; }
Output
Absolute value of -99887654321 is: 99887654321 Absolute value of 99887654321 is: 99887654321