Typical char ranges on most systems:
- Type: char, Range: -127 to 127 or 0 to 255
- Type: unsigned char, Range: 0 to 255
- Type: signed char, Range: -127 to 127
Whether char
is signed or unsigned is implementation-defined. You can check using std::is_signed<char>()
. In your case, it's implicitly signed, and the compiler detected that you are implicitly converting from a positive integer (10110000 = 176) to a signed character value (where 10110000 is -90). The warning won't be generated if the values are less than or equal to 127 (try it!).
If you want to avoid the implicit conversion (narrowing conversion), you can explicitly specify that it's unsigned:
unsigned char m1[3]{ 176, 118, 1 };
If you want to use signed characters, you should preferably use the signed
modifier, rather than relying on the implementation:
signed char m1[3]{ b, 118, 1 }; // where b is less than or equal to 127
With the {}-initialization, the compiler should - at least - diagnose it as a warning, which makes the program ill-formed. But again, that depends on the compiler and options used. If you go to https://gcc.godbolt.org/ and compile your code with different compilers/options, you could see the difference.
Some examples:
For the following code:
char m1[3] = {176, 118, 1 };
- with x86-64 gcc 6.1 you get an error:
error: narrowing conversion of '176' from 'int' to 'char' inside { } [-Wnarrowing]
. However, when you use the flag -Wno-narrowing
you don't get it, but still, your program is ill-formed and you don't want that.
- with x86-64 gcc 4.8.1 you get no errors, no warnings. However, when using, for example, the options
-Wno-narrowing
or -Werror=narrowing
, you can see that it's rejected with a warning or error respectively.
With the code:
int b1 = 176;
char m1[3] = {b1, 118, 1 };
You get a different behavior with different compiler versions, but still, the program is ill-formed.
In general, using options like -Wnarrowing
, -Wall
, or -Werror=narrowing
with whatever version (I guess, I didn't check all of them) of the compiler, should point out the narrowing conversion, which means that your program is ill-formed and you don't want that.
I hope this helps!