Tue Jul 10 09:18:39 EDT 2012
Overflow is undefined for signed ints
While Two's complement arithmetic has little secrets for me, I was
surprised to learn that it's not so well-defined in C as I thought.
The reason seems to be that for unsigned ints, the behaviour is easily
expressed in terms of the C '%' modulo operator, as operations modulo
1^n where n is the bit size.
However, for signed ints this doesn't work because the same
interpretation (modulo a positive number) should not change the sign.
While there is definitely a "wrap around" for signed ints, it can not
be expressed (simply) in terms of the C modulo '%' operator, which is
probably the reason it is left unspecified.
When unsigned and signed are mixed, the result is unsigned. That
makes sense, since it allows an accumulator to be unsigned, and
increments to the accumulator be unsigned or signed.
Conclusion: representing modulo arithmetic in C using overflow needs
to be done using unsigned ints. It will "probably" work with signed
ints, but that relies on unspecified behavior.