GCC与Clang之间的不同行为

时间:2017-11-27 11:53:05

标签: c++ gcc g++ clang

代码:

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

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

0 个答案:

没有答案