c – 为什么`bool b = 2`运行良好但是`bool b = {2}`会产生转换范围缩小的警告?

前端之家收集整理的这篇文章主要介绍了c – 为什么`bool b = 2`运行良好但是`bool b = {2}`会产生转换范围缩小的警告?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
使用C 11中的{}初始化程序初始化bool b = {2}会产生以下警告消息:
warning: narrowing conversion of ‘2’ from ‘int’ to ‘bool’ inside { } [-Wnarrowing]

但是,使用旧式bool b = 2没有这样的问题.这背后的原因是什么?

更新:我使用g -std = c 11编译了代码,它给了我警告.如果我添加选项-pedantic-errors,则警告将成为错误.

解决方法

缩小初始化列表中的数据类型会使您的c 11程序生成错误,在这种情况下,编译器可以发出警告或继续运行.

有趣的是,你实际上可以将它改为bool b = {1}并且没有警告,我假设因为bool的值保证在整数类型中转换为0和1.

这是确认错误的标准报价.

A narrowing conversion is an implicit conversion — from a floating-point type to an integer type,or — from long double to double or float,or from double to float,except where the source is a constant expression and the actual value after conversion is within the range of values that can be represented (even if it cannot be represented exactly),or — from an integer type or unscoped enumeration type to a floating-point type,except where the source is a constant expression and the actual value after conversion will fit into the target type and will produce the original value when converted back to the original type,or — from an integer type or unscoped enumeration type to an integer type that cannot represent all the values of the original type,except where the source is a constant expression and the actual value after conversion will fit into the target type and will produce the original value when converted back to the original type. As indicated above,such conversions are not allowed at the top level in list-initializations

猜你在找的C&C++相关文章