代码之家  ›  专栏  ›  技术社区  ›  chaosink

GCC和Clang之间的不同行为

  •  2
  • chaosink  · 技术社区  · 7 年前

    代码:

    #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
    
    1 回复  |  直到 7 年前
        1
  •  6
  •   Bathsheba    7 年前

    转换 浮点类型 unsigned char 其中浮点值在 无符号字符 未定义 .