在{}中将'((((int)a)+ -1)'从'int'转换为'int16_t {aka short int}'

时间:2019-02-19 16:01:04

标签: c++

我有以下“ test.cpp”文件:

#include <cstdint>

struct Struct
{
    int16_t val;
};

int main()
{
        int16_t a = 0;
        //Struct b = {.val = a}; // No warning
        Struct b = {.val = a-1}; // Warning
        (void)b;
        return 0;
}

使用'g ++ -std = c ++ 11 -o test test.cpp'进行编译时,出现以下警告:

test.cpp: In function ‘int main()’:
test.cpp:12:29: warning: narrowing conversion of ‘(((int)a) + -1)’ from ‘int’ to ‘int16_t {aka short int}’ inside { } [-Wnarrowing]
         Struct b = {.val = a-1};
                             ^

是否有摆脱它的方法?

2 个答案:

答案 0 :(得分:3)

减去1时,a的类型将提升为int。 您可以通过对整个表达式执行static_cast来解决此问题:

    Struct b = { .val = static_cast<int16_t>(a - 1) };

请注意,如果使用普通的int类型来完成某些平台(例如x86)的算术运算,可能会更快。

答案 1 :(得分:1)

    Struct b = {.val = (int16_t)(a-1)}; // cast as expected, by default formula produces int

请注意,如果我使用-pedantic进行编译:

pi@raspberrypi:/tmp $ g++ -pedantic c.cc
c.cc: In function ‘int main()’:
c.cc:12:20: warning: ISO C++ does not allow C99 designated initializers [-Wpedantic]
         Struct b = {.val = (int16_t)(a-1)}; // Warning

更好地拥有

Struct b = {(int16_t)(a-1)}; // no warning even with -pedantic