Reputation: 426
I understand the reason why C++ define INT_MIN as (-2147483647 - 1), but why don't they just use 1<<31 ? That prevent the overflow and also easy to understand.
Upvotes: 4
Views: 644
Reputation: 126502
That prevent the overflow and also easy to understand
How could it prevent the overflow, if by left-shifting a positive number you are trying to obtain a negative one? ;)
Keep in mind, that signed integer overflow is Undefined Behavior. Per paragraph 5.8/2 of the C++11 Standard:
The value of
E1 << E2
isE1
left-shiftedE2
bit positions; vacated bits are zero-filled. [...] Otherwise, ifE1
has a signed type and non-negative value, andE1×2^E2
is representable in the corresponding unsigned type of the result type, then that value, converted to the result type, is the resulting value; otherwise, the behavior is undefined.
Also, per paragraph 5/4:
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. [...]
Upvotes: 7
Reputation: 272657
Because 1 << 31
invokes undefined behaviour (assuming 32-bit int
).
Upvotes: 4