I try to compile the following code with gcc
and C++11
enabled:
unsigned int id = 100;
unsigned char array[] = { id % 3, id % 5 };
I get these warnings:
narrowing conversion of ‘(id % 3u)’ from ‘unsigned int’ to ‘unsigned char’ inside { } [-Wnarrowing]
Is there a way to help the compiler find out that the result of id % 3 fits into an unsigned char?
In this specific case making
id
const or constexpr will fix the problem:since there is an exception for the case where you have a constant expression whose result after conversion will fit into the target type.
In the more general case you may also use static_cast to cast the result to unsigned char:
We can find he exception for constant expressions and narrowing conversions in the draft C++ standard section
8.5.4
List-initialization which says:and include the following bullet (emphasis mine):
Note, the wording changed from the original draft C++11 standard to what I quote above due to defect report 1449.