3
votes

I'm trying to compile some fairly simple C++ code with GCC 6, but getting a narrowing conversion warning. This is problematic because we treat warnings as errors.

struct S {
    short int a;
    short int b;
};

short int getFoo();
short int getBar();

std::array<S, 2> arr = {{
    {5, getFoo()},
    {3, getFoo() + getBar()}   // Narrowing conversion here?
}};

You can see this code in action at https://godbolt.org/g/wHNxoc. GCC says getFoo() + getBar() is narrowing from an int down to a short int. What is causing the upcast to an int? Is there any good solution here short of a forced cast to short int?

1

1 Answers

8
votes

It is due to the integral promotion:

prvalues of small integral types (such as char) may be converted to prvalues of larger integral types (such as int). In particular, arithmetic operators do not accept types smaller than int as arguments, and integral promotions are automatically applied after lvalue-to-rvalue conversion, if applicable. This conversion always preserves the value.

As a consequence, getFoo() + getBar() has a type of int, which leads to the aforementioned warning.

To suppress a warning, you might make use of static_cast:

static_cast<short>(getFoo() + getBar())