c - 有符号整数溢出是否定义了未定义的行为或实现?

标签 c undefined-behavior implementation-defined-behavior

#include <limits.h>

int main(){
 int a = UINT_MAX; 
 return 0;
}
我这个 UB 或实现定义?
链接说它的 UB
https://www.gnu.org/software/autoconf/manual/autoconf-2.63/html_node/Integer-Overflow-Basics
Allowing signed integer overflows in C/C++
链接说它的实现定义了
http://www.enseignement.polytechnique.fr/informatique/INF478/docs/Cpp/en/c/language/signed_and_unsigned_integers.html
转换规则说:

Otherwise, the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised.


我们不是在转换 max unsigned valuesigned value ?
在我看来,gcc 只是截断了结果。

最佳答案

两个引用文献都是正确的,但它们没有解决相同的问题。int a = UINT_MAX;不是有符号整数溢出的实例,此定义涉及从 unsigned int 的转换至 int具有超出类型 int 范围的值.正如 École polytechnique 的网站所引述的那样,C 标准将行为定义为实现定义。

#include <limits.h>

int main(){
    int a = UINT_MAX;    // implementation defined behavior
    int b = INT_MAX + 1; // undefined behavior
    return 0;
}
这是来自 C 标准的文本:

6.3.1.3 Signed and unsigned integers

  1. When a value with integer type is converted to another integer type other than _Bool, if the value can be represented by the new type, it is unchanged.

  2. Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type.

  3. Otherwise, the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised.


一些编译器有一个命令行选项来将有符号算术溢出的行为从未定义的行为更改为实现定义的行为:gccclang支持 -fwrapv强制整数计算以 232 或 264 为模执行,具体取决于有符号类型。这阻止了一些有用的优化,但也阻止了一些可能破坏无辜代码的违反直觉的优化。有关一些示例,请参阅此问题:What does -fwrapv do?

关于c - 有符号整数溢出是否定义了未定义的行为或实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67755339/

相关文章:

c++ - 为什么 boost::hana::tuple_c 的类型是实现定义的?

c++ - sizeof(bool) 是否在 C++ 语言标准中定义?

带有内联汇编代码的 %hi() 和 %lo() 编译错误

c - 使用动态数组进行 realloc() 后的意外行为

c - 互补误差函数 erfcf() 的矢量化实现

c - 与弦作斗争。我的功能出了什么问题?

multithreading - 为什么这个小的 c++11 多线程程序会出现段错误

c++ - __builtin_ctz(0)或__builtin_clz(0)有多不确定?

c - 本地套接字绑定(bind)错误

c++ - 为什么我不应该#include <bits/stdc++.h>?