G+: Here's today's fun bit of corner case behavior …

David Coles
Here's today's fun bit of corner case behavior in C:

int a = -2147483648;
printf(" a = %d\n", a);
printf(" -a = %d\n", -a);

Running this prints:
a = -2147483648
-a = -2147483648

Wait what!? Who broke the number system?!

Why does this happen? Here's a hint: -2147483648 is INT_MIN on this system.

Due to the asymmetry of the 2s-complement number system, there's no positive 2147483648 int value and thus you can't represent a's negated value. Thus it overflows back to a (though technically this is undefined behavior).

What's the solution in this case? Either ensure the magnitude of your values are small enough never will try and negate INT_MIN or do something like `(a==INT_MIN ? INT_MAX : -a)`.

Want to see something a little more shocking? Try printing the result of `abs(a)`!

(+1's) 2
Jonathan N

David Coles
+Jonathan Newnham Nice! Floating point numbers are equal parts brilliance and black magic, so given how much trouble integer arithmetic causes us poor programmers I'm surprised every program with a float or a double hasn't caught fire yet!