Feb 22, 2016

[C++] Is signed integer overflow still undefined behavior in C++?

http://kristerw.blogspot.com/2016/02/how-undefined-signed-overflow-enables.html

http://stackoverflow.com/a/16188846


is still overflow of these types an undefined behavior?
Yes. Per Paragraph 5/4 of the C++11 Standard (regarding any expression in general):
If during the evaluation of an expression, the result is not mathematically defined or not in the range of representable values for its type, the behavior is undefined. [...]
The fact that a two's complement representation is used for those signed types does not mean that arithmetic modulo 2^n is used when evaluating expressions of those types.
Concerning unsigned arithmetic, on the other hand, the Standard explicitly specifies that (Paragraph 3.9.1/4):
Unsigned integers, declared unsignedshall obey the laws of arithmetic modulo 2^n where n is the number of bits in the value representation of that particular size of integer
This means that the result of an unsigned arithmetic operation is always "mathematically defined", and the result is always within the representable range; therefore, 5/4 does not apply. Footnote 46 explains this:
46) This implies that unsigned arithmetic does not 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 unsigned integer type.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.