gpt4 book ai didi

c++ - GCC 和 Clang 之间的不同行为

转载 作者:搜寻专家 更新时间:2023-10-31 00:08:43 25 4
gpt4 key购买 nike

代码:

#include <cstdio>

int main() {
unsigned char a = -300.f;
printf("%d\n", a);
}

GCC 编译:

g++ test.cpp -o test -std=c++11
test.cpp: In function ‘int main()’:
test.cpp:4:21: warning: overflow in implicit constant conversion [-Woverflow]
unsigned char a = -300.f;
^

海合会结果:

0

海湾合作委员会版本:

gcc (Ubuntu 5.4.0-6ubuntu1~16.04.5) 5.4.0 20160609

Clang 编译:

clang++ test.cpp -o test -std=c++11
test.cpp:4:21: warning: implicit conversion from 'float' to 'unsigned char' changes value from 300 to 255
[-Wliteral-conversion]
unsigned char a = -300.f;
~ ^~~~~
1 warning generated.

Clang 结果:

160

clang 版本:

clang version 3.8.0-2ubuntu4 (tags/RELEASE_380/final)

也许标准没有定义这种行为。


添加-fsanitize=undefined后:

GCC 结果(相同):

0

Clang结果(48!?):

test.cpp:4:20: runtime error: value -300 is outside the range of representable values of type 'unsigned char'
48

最佳答案

浮点类型 转换为 unsigned char 时浮点值超出 unsigned char 范围的行为是未定义

请注意,这与原始类型是更宽整数类型的情况不同。

关于c++ - GCC 和 Clang 之间的不同行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47510365/

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