On Mon, 11 Jul 2005, Dave Korn wrote:
There was recently a very long thread about the overflow behaviour of
signed integers in C. Apparently this is undefined according to the C
standard. I searched the standard on this matter, and while I did find
some paragraphs that described how unsigned integers must wrap around upon
overflow, I couldn't find anything explicit about signed integers.
Dave, Nathan and Paul: thanks for the quick replies.
The difference between signed and unsigned integer overflow is a little
unclearly expressed, I think.
3.4.3/3 says:
"EXAMPLE An example of undefined behavior is the behavior on integer
overflow"
6.5/5 says:
"If an _exceptional condition_ occurs during the evaluation of an
expression (that is, if the result is not mathematically defined or not
in the range of representable values for its type), the behavior is
undefined."
These two paragraphs would seem to indicate that overflow is undefined for
both signed and unsigned integers.
But then 6.2.5 para 9, sentence 2 says:
"A computation involving unsigned operands can never overflow, because a
result that cannot be represented by the resulting unsigned integer
type is reduced modulo the number that is one greater than the largest
value that can be represented by the resulting type."
Which requires that unsigned ints must wrap on overflow. (Actually, I
guess it defines "overflow" such that unsigned ints never "overflow", so
3.4.3/3 and 6.5/5 don't apply!)
But I think the paragraphs together are good enough to communicate that:
unsigned ints must wrap on overflow, signed ints need not. Thanks again
for your help.
N