Search code examples
c++clang

C++ Adding two uint16_t does not compile in clang


Why can't the following code be compiled in clang?

#include <cstdint>
int main(int argc, char *argv[]) {
  uint16_t one{1};
  uint16_t two{one + one};
  return 0;
}

See compiler explorer. Error message:

<source>:4:16: error: non-constant-expression cannot be narrowed from type 'int' to 'uint16_t' (aka 'unsigned short') in initializer list [-Wc++11-narrowing]
    4 |   uint16_t two{one + one};
      |                ^~~~~~~~~
<source>:4:16: note: insert an explicit cast to silence this issue
    4 |   uint16_t two{one + one};
      |                ^~~~~~~~~
      |                static_cast<uint16_t>( )
1 error generated.
Compiler returned: 1

Solution

  • The expression one + one is of type int because the default arithmetic conversions promote operands smaller than int to int before performing the addition.

    Reference: Why must a short be converted to an int before arithmetic operations in C and C++?

    Thus, you need to cast int to uint16_t manually.

    uint16_t two = static_cast<uint16_t>(one + one);