加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 为什么gcc警告只为统一初始化缩小转换?

发布时间:2020-12-16 09:21:23 所属栏目:百科 来源:网络整理
导读:我试图将长类型变量转换为具有 uniform initialization 的int类型变量,没有它.但是我只能通过统一初始化获得编译器警告.这是为什么?为什么gcc不警告两种情况?我也尝试过clang并得到了类似的结果. 这是代码 #include iostreamint main() { long l = 1; int
我试图将长类型变量转换为具有 uniform initialization的int类型变量,没有它.但是我只能通过统一初始化获得编译器警告.这是为什么?为什么gcc不警告两种情况?我也尝试过clang并得到了类似的结果.

这是代码

#include <iostream>

int main() {
    long l = 1;
    int i1 = l;
    int i2 = { l };

    std::cout << i1 << std::endl;
    std::cout << i2 << std::endl;

    return 0;
}

我得到的唯一一个警告

$g++ -Wall -Wextra 1.cpp
1.cpp: In function ‘int main()’:
1.cpp:6:16: warning: narrowing conversion of ‘l’ from ‘long int’ to ‘int’ inside { } [-Wnarrowing]
   int i2 = { l };

解决方法

因为标准说,narrowing conversions limit仅指定列表初始化(自C 11起).

list-initialization limits the allowed implicit conversions by
prohibiting the following:

  • conversion from a floating-point type to an integer type
  • conversion from a long double to double or to float and conversion from double to float,except where the source is a constant expression
    and overflow does not occur
  • conversion from an integer type to a floating-point type,except where the source is a constant expression whose value can be stored
    exactly in the target type
  • conversion from integer or unscoped enumeration type to integer type that cannot represent all values of the original,except where source
    is a constant expression whose value can be stored exactly in the
    target type

对于其他初始化方法(使用括号或等号),不应用(添加)缩小转换限制规则;因为这可能会破坏很多遗留代码.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读