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)`!
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)`!