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.

有帮助吗?

解决方案

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 is E1 left-shifted E2 bit positions; vacated bits are zero-filled. [...] Otherwise, if E1 has a signed type and non-negative value, and E1×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. [...]

其他提示

Because 1 << 31 invokes undefined behaviour (assuming 32-bit int).

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top