What does the C++ language definition promise about casting a char to bool then back to char again?
char original = 255;
bool next = original;
char final = next;
Also, what do most compilers do in this case beyond what the language guarantees?
This will give a value of zero or one, depending on whether the original value was zero or non-zero.
Converting to bool
gives a value of true
or false
:
4.12 A zero value, null pointer value, or null member pointer value is converted to
false
; any other value is converted totrue
.
Converting back to char
converts false
to zero, and true
to one:
4.7/4 If the source type is
bool
, the valuefalse
is converted to zero and the valuetrue
is converted to one.