The abs() Function

Seriously, why do programmers need an abs() function? It’s available in just about every programming language; if you view an alphabetic list of functions, abs() is probably the first one. Yet, what’s the point of a function that simply converts negative values to positive values?

The point is that you find yourself needing positive values from time to time and the abs() function guarantees that result.

For example, you subtract variable b from a, which returns the difference. The result could be positive or negative. To ensure that its positive, you use the abs() function:

difference = abs( a - b );

The abs() function is defined in the stdlib.h header file. It accepts integer values as input and returns a positive integer value.

For floating-point values, use the fabs() function, defined in the math.h header file. It accepts double values as input and returns a positive double value. Other variations are available on these absolute value functions; refer to the man page entries for abs() and fabs().

The following code uses the abs() function to return the positive (absolute) difference between values in a loop that runs from -10 and steps up to +10:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int a;

    for(a=-10;a<=10;a++)
    {
        printf("0 - %3d = %3d abs(%3d)\n",
                a,
                0-a,
                abs(0-a));
    }

    return(0);
}

The abs() function is nestled in the printf() statement at Line 10. Here’s the output:

0 - -10 =  10 abs( 10)
0 -  -9 =   9 abs(  9)
0 -  -8 =   8 abs(  8)
0 -  -7 =   7 abs(  7)
0 -  -6 =   6 abs(  6)
0 -  -5 =   5 abs(  5)
0 -  -4 =   4 abs(  4)
0 -  -3 =   3 abs(  3)
0 -  -2 =   2 abs(  2)
0 -  -1 =   1 abs(  1)
0 -   0 =   0 abs(  0)
0 -   1 =  -1 abs(  1)
0 -   2 =  -2 abs(  2)
0 -   3 =  -3 abs(  3)
0 -   4 =  -4 abs(  4)
0 -   5 =  -5 abs(  5)
0 -   6 =  -6 abs(  6)
0 -   7 =  -7 abs(  7)
0 -   8 =  -8 abs(  8)
0 -   9 =  -9 abs(  9)
0 -  10 = -10 abs( 10)

The abs() function always returns a positive value.

Be on the lookout for functions that require positive values as input. That’s one of those times you must use an absolute value function when you might not think you need one. So when you read a function’s description and it requires positive value as input, use the abs() function to ensure that any variable passed is positive.

Leave a Reply