I understand that a char value cannot be represented as 176, but some byte systems are unsigned (0-255) while others are signed (-128 to 127). In this case I'm working with unsigned, so I just wanted to create a simple byte message array, but I get this error when trying to place a higher value than 127, but if I declare it as an int first it avoids the error. Can someone explain in detail why this works?
Method 1: Doesn't work. I get this error: narrowing conversion of ‘176’ from ‘int’ to ‘char’
char m1[3]{ 176, 118, 1 };
Method 2: This works
int b1 = 176;
char m1[3]{ b1, 118, 1 };
When using curly braces for initialization (aka "uniform initialization") then narrowing conversions are not allowed. Otherwise they are and the value is just silently truncated.
Most compilers have warning options that you can enable that will catch many (but not all) instances where truncation happens. They usually also have options that can turn such warnings into errors. You should use those options.
If you want to work with bytes then std::byte is arguably the correct type to use. Or (if you cannot use that) std::uint8_t.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With