Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
abs(), labs(), llabs() functions in C/C++
The C standard library provides different functions to calculate the absolute value of integers based on their data types. The abs(), labs(), and llabs() functions handle int, long, and long long data types respectively, returning the non-negative value of their arguments.
Syntax
int abs(int n); long labs(long n); long long llabs(long long n);
The abs() Function
The abs() function returns the absolute value of an integer argument. It is defined in stdlib.h and works with int type data −
Example
#include <stdio.h>
#include <stdlib.h>
int main() {
int x = -145;
int y = 145;
printf("Absolute value of %d is: %d\n", x, abs(x));
printf("Absolute value of %d is: %d\n", y, abs(y));
return 0;
}
Absolute value of -145 is: 145 Absolute value of 145 is: 145
The labs() Function
The labs() function returns the absolute value of a long integer. It handles larger integer values than abs() −
Example
#include <stdio.h>
#include <stdlib.h>
int main() {
long x = -9256847L;
long y = 9256847L;
printf("Absolute value of %ld is: %ld\n", x, labs(x));
printf("Absolute value of %ld is: %ld\n", y, labs(y));
return 0;
}
Absolute value of -9256847 is: 9256847 Absolute value of 9256847 is: 9256847
The llabs() Function
The llabs() function returns the absolute value of a long long integer, supporting the largest integer data type in C −
Example
#include <stdio.h>
#include <stdlib.h>
int main() {
long long x = -99887654321LL;
long long y = 99887654321LL;
printf("Absolute value of %lld is: %lld\n", x, llabs(x));
printf("Absolute value of %lld is: %lld\n", y, llabs(y));
return 0;
}
Absolute value of -99887654321 is: 99887654321 Absolute value of 99887654321 is: 99887654321
Key Points
- All functions return the same value if the argument is already positive.
- Choose the appropriate function based on your data type to avoid overflow issues.
- These functions are declared in
stdlib.hheader file.
Conclusion
The abs(), labs(), and llabs() functions provide type-specific absolute value calculations in C. Using the correct function for your data type ensures proper handling of large numbers and prevents potential overflow errors.
