c – 不一致的警告“从’const unsigned char’转换为’const float’需要缩小转换”

前端之家收集整理的这篇文章主要介绍了c – 不一致的警告“从’const unsigned char’转换为’const float’需要缩小转换”前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
Visual C 2017和 gcc 5.4生成从’const unsigned char’到’const float’的转换需要对B行进行缩小转换警告,但在此代码段中不需要对A行进行转换:
#include <iostream>

int main() {
    const unsigned char p = 13;
    const float         q = p;  // Line A

    std::cout << q << '\n';

    const unsigned char c[3] = {0,1,255};
    const float         f[3] = {c[2],c[0],c[1]};  // Line B

    for (auto x:f)
        std::cout << x << '\n';
}

这个警告有效吗?为什么B线的处理方式与A线不同?

解决方法

警告有效,aggregate initialization禁止C 11 narrowing conversions;但未在 copy initialization中应用(如前所述).

If the initializer clause is an expression,implicit conversions are allowed as per copy-initialization,except if they are narrowing (as in list-initialization) (since C++11).

Until C++11,narrowing conversions were permitted in aggregate initialization,but they are no longer allowed.

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

  • 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

BTW:c [0],c [1]和c [2]是not constant expressions;你可以将数组声明为constexpr,即constexpr unsigned char c [3] = {0,255};.然后应用异常,Line B也可以正常工作.

原文链接:https://www.f2er.com/c/119385.html

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