我理解 C++ 将 INT_MIN 定义为 (-2147483647 - 1) 的原因,但他们为什么不直接使用 1<<31 呢?既防止溢出又易于理解。
最佳答案
That prevent the overflow and also easy to understand
如果通过左移一个正数试图得到一个负数,它如何防止溢出? ;)
请记住,有符号整数溢出是未定义行为。根据 C++11 标准的第 5.8/2 段:
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.
此外,根据第 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. [...]
关于c++ - 为什么 C++ 不将 INT_MIN 定义为 (1<<31),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16884370/