abs() / labs() / div()
Functions for computing the absolute value of an integer, and for computing the quotient and remainder in a single operation. Both are defined in <stdlib.h>. For the absolute value of a floating-point number, use fabs() from <math.h>.
Syntax
// Returns the absolute value of an int. int abs(int n); // Returns the absolute value of a long. long labs(long n); // Returns the absolute value of a long long (C99 and later). long long llabs(long long n); // Computes the quotient and remainder of an int division at once, returned as a div_t struct. div_t div(int numer, int denom); // Computes the quotient and remainder of a long division at once, returned as an ldiv_t struct. ldiv_t ldiv(long numer, long denom);
div_t / ldiv_t Structs
| Member | Type (div_t) | Description |
|---|---|---|
| quot | int | The quotient of the division (numer / denom). |
| rem | int | The remainder of the division (numer % denom). |
Sample Code
#include <stdio.h>
#include <stdlib.h>
int main(void) {
// Use abs to get the absolute value of an int.
printf("abs(-10) = %d\n", abs(-10)); // Prints: abs(-10) = 10
printf("abs(7) = %d\n", abs(7)); // Prints: abs(7) = 7
// Use labs to get the absolute value of a long.
long big = -123456789L;
printf("labs(%ld) = %ld\n", big, labs(big)); // Prints the positive value.
// Use div to get the quotient and remainder at once (no need to write / and % separately).
div_t result = div(17, 5);
printf("17 / 5 = quotient %d remainder %d\n", result.quot, result.rem);
// Prints: 17 / 5 = quotient 3 remainder 2
// A typical use of abs: computing the distance between two coordinates.
int x1 = 3, x2 = -4;
int distance = abs(x2 - x1);
printf("Distance between x1 and x2: %d\n", distance); // Prints: Distance between x1 and x2: 7
// Use div to convert minutes into hours and minutes.
int total_minutes = 137;
div_t time = div(total_minutes, 60);
printf("%d minutes = %d hour(s) %d minute(s)\n", total_minutes, time.quot, time.rem);
// Prints: 137 minutes = 2 hour(s) 17 minute(s)
return 0;
}
Notes
The absolute value of INT_MIN (the minimum value of int) cannot be represented as an int, so the result of abs(INT_MIN) is undefined behavior. If this value may appear in your input, use long or long long, or add a check beforehand.
div() computes both the quotient and remainder in a single operation. Depending on compiler optimizations, it may generate the same code as separate / and % operators, but it is also useful for making the intent of the code explicit.
For the absolute value of a floating-point number, use fabs().
If you find any errors or copyright issues, please contact us.