When I try to compile this code
struct T
{
unsigned char x;
};
int main()
{
unsigned char a = 10;
unsigned char b = 1;
T t = {a + b};
return 0;
}
I get this error:
error: narrowing conversion of '(((int)a) + ((int)b))' from 'int' to 'unsigned char' inside { } [-Wnarrowing]|
Can anyone explain me why?
The operands to your addition expression are undergoing integral promotion.
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.
Your a
and b
are being promoted to int
or unsigned int
, added, and then converted back down to unsigned char
.
If the conversion is expected program behavior (from your point of view as the designer), you can explicitly cast it to the type you want. An explicit cast is not a narrowing conversion. An implicit cast is. So if we change the implicit cast to an explicit cast, the program is no longer ill-formed.
T t = { static_cast<unsigned char>(a + b) };