Surprise in math.h

Quick Quiz: What does the following code output:

#include <math.h>
#include <stdint.h>
#include <stdio.h>

int main(int argc, char **argv)
{
    int i = INT32_MIN;
    printf("i is: %d\n", i);
    printf("abs(i) is: %d\n", abs(i));
}

Select the following to see the result...

stephen@frank:/tmp$ gcc test.c -o test
stephen@frank:/tmp$ ./test 
i is: -2147483648
abs(i) is: -2147483648

Woah! This comes from the 2s complement representation of INT32_MIN. It's 1 followed by all zeros. When abs() does the standard invert-all-bits-then-add-one technique for turning a negative into a positive it turns INT32_MIN into... INT32_MIN!

Thanks to http://www.youtube.com/watch?v=wDN_EYUvUq0

Posted on 23 May 2009
With thanks to https://github.com/jamesyu/jamesyu_jekyll_template