gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 23:33:06 25 4
gpt4 key购买 nike

#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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com