c++ - 为什么 C++ 不将 INT_MIN 定义为 (1<<31)

标签 c++ numeric-limits

我理解 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 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.

此外,根据第 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/

相关文章:

c++ - 是否可以使用 Dtrace 探测 C++ 类中的条目?

c++ - 如何在共享内存中分配 CGAL Halfedge 结构?

c++ - 在 C++ 中对对象 vector 进行排序

c++ - val != std::numeric_limits<double>::infinity() 或 !isinf(val) 或 isfinite(val)

c++ - 为什么这个 'if' 语句循环?

c++ - 编译器无法识别自定义 numeric_limits 成员函数

c++ - numeric_limits 中有错误还是我只是感到困惑?

c++ - 为什么 numeric_limit<T>::min/max 不是常量?

c++ - 为什么 numeric_limits::min 为 int 返回负值,但为 float/double 返回正值?

c++ - 当数组内容改变时更新指向数组元素的指针