【问题标题】:Is there an 'Integral constant overflow' warning in clang?铿锵声中是否有“积分常数溢出”警告?
【发布时间】:2014-01-13 14:06:28
【问题描述】:

考虑以下 sn-ps:

short x = 2000000000;

short x = (short)2000000000;

int x = 1000000000 * 1000000000;

我们可以在 Clang 中得到警告(/错误)吗?如何?从什么版本开始?

谢谢, 西普里安。

【问题讨论】:

    标签: c clang constants integer-overflow compile-time-constant


    【解决方案1】:

    至少从 clang 3.3 开始,您在这两种情况下都会收到警告,甚至无需尝试:

    /* main.c */
    short x = 2000000000;
    int y = 1000000000 * 1000000000;
    
    int main()
    {
        return 0;
    }
    

    编译:

    $ clang -c main.c
    main.c:1:11: warning: implicit conversion from 'int' to 'short' changes value
          from 2000000000 to -27648 [-Wconstant-conversion]
    short x = 2000000000;
          ~   ^~~~~~~~~~
    main.c:2:20: warning: overflow in expression; result is -1486618624 with type
          'int' [-Winteger-overflow]
    int y = 1000000000 * 1000000000;
                       ^
    2 warnings generated.
    

    【讨论】:

    • 谢谢,这是一个很好的答案。您能否添加您使用的警告标志?您还可以补充一下当您进行像 short x = (short) 2000000000; 这样的显式转换时会发生什么? ?我将编辑我的问题以包含该案例。谢谢!
    • $ clang -c main.c 是编译命令。没有警告标志。 (short) 2000000000 不会引发隐式转换警告,因为转换是显式的:强制转换意味着“就这么做”。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-02
    • 2012-01-08
    相关资源
    最近更新 更多