代码:
#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;
^
GCC结果:
0
GCC版本:
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.
叮当声结果:
160
叮当声版本:
clang version 3.8.0-2ubuntu4 (tags/RELEASE_380/final)
也许标准没有定义这种行为。
添加后
-fsanitize=undefined
ï¼
GCC结果(相同)
0
叮当声结果(48!)
test.cpp:4:20: runtime error: value -300 is outside the range of representable values of type 'unsigned char'
48