Search code examples
c++typestype-conversionnarrowing

Why is there a narrowing conversion warning from int to short when adding shorts? (C++)


I have a code similar to this for the following array:

long int N = 424242424242; //random number
short int* spins = new short int spins[N];
std::fill(spins, spins+N, 1);

Now let's suppose for some reason I want to add a couple of elements of that array into a short int called nn_sum:

short int nn_sum = spins[0] + spins[1];

However, when I do this on CLion IDE, Clang-Tidy marks it yellow and tells me:

Clang-Tidy: Narrowing conversion from 'int' to signed type 'short' is implementation-defined

Why is this happening? Why is there any narrowing at all? Does C++ convert the shorts to ints when adding them? If so why, and is there something I can do to make it work better? Maybe even ditch the shorts entirely?

Keep in mind that I have code like this in a very computationally intensive part of the application so I want to make it as efficient as possible. Any other suggestion would also be appreciated.


Solution

  • This happens because of integer promotion. The result of adding two short values is not short, but int.

    You can check this with cppinsights.io:

    short a = 1;
    short b = 2;
    auto c = a + b;  // c is int
    

    Demo: https://cppinsights.io/s/68e27bd7