簡體   English   中英

GCC和Clang之間的行為不同

[英]Different behaviors between GCC and 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

lang編譯

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

lang版本:

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

也許標准沒有定義這種行為。


添加-fsanitize=undefined

GCC結果(相同):

0

lang結果(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的范圍)的行為是不確定的

請注意,這與原始類型是較寬的整數類型的情況不同。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM