Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can I pass an int with a value higher than 127 into a char array, but not directly?

Tags:

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 };
like image 594
karamazovbros Avatar asked Nov 08 '18 18:11

karamazovbros


1 Answers

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.

like image 194
Jesper Juhl Avatar answered Nov 15 '22 04:11

Jesper Juhl