abs gotcha

Am I the only one who didn’t know about this?

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

int main(int argc, char **argv)
{
    printf("%d\n", abs(INT_MIN));
    return 0;
}

Which gives:

davemc@zaphod:~/devel$ gcc -o abstest abstest.c
davemc@zaphod:~/devel$ ./abstest
-2147483648

The abs function, in C, is undefined if you call it with INT_MIN (because a two’s-compliment 32-bit int can be -231 but not +231). In Java, it’s specified to return Integer.MIN_VALUE.

I feel slightly betrayed that abs can return a negative number. Actually, I feel more betrayed that this isn’t a classic drummed-into-our-heads-in-every-programming-guide-and-uni-course-ever gotcha.

In other news: Google doesn’t do what you expect if you search for “man abs”.

Leave a Comment