Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading