Search code examples
c++castingbooleanlanguage-lawyerroundtrip

What happens to char round-trip cast through a bool?


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?


Solution

  • 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 to true.

    Converting back to char converts false to zero, and true to one:

    4.7/4 If the source type is bool, the value false is converted to zero and the value true is converted to one.