Possible Duplicate:
C++ underflow and overflow
I have following code in c++:
int temp = std::numeric_limits<int>::max();
temp++;
Am I sure that after incrementation the result will always be <0?
Thanks
Possible Duplicate:
C++ underflow and overflow
I have following code in c++:
int temp = std::numeric_limits<int>::max();
temp++;
Am I sure that after incrementation the result will always be <0?
Thanks
No, it's not guaranteed. C++03 has this to say in 5 Expressions, paragraph 5
:
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, unless such an expression is a constant expression, in which case the program is ill-formed. [Note: most existing implementations of C + + ignore integer overflows].
Further, there is nothing in 5.7 Additive operators
that modifies this behaviour. This is unchanged in C++11.
That's for signed types, which is what you asked about in your question.
If you're also interested in unsigned types, section 3.9.1 Fundamental types, paragraph 4
states:
Unsigned integers, declared unsigned, shall obey the laws of arithmetic modulo 2n where n is the number of bits in the value representation of that particular size of integer (see footnote 41).
Footnote 41: 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, overflow in signed integral types results in undefined behavior.
EDIT: In addition to paxdiablo's quote:
3.9.1.
Note 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.