Pergunta

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?

Foi útil?

Solução

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.

Outras dicas

Integral values converted to bool result in either true or false (4.12), and bool converted to integral values results in either 1 or 0 (4.5(6)). See Chapter 4 (Standard Conversions).

When converting to bool zero and null are converted to false, and everything else is converted to true. When converting from bool false is converted to zero and true is converted to one.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top