Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 514
WilliamKF Avatar asked Jan 31 '12 15:01

WilliamKF


People also ask

Is bool the same as char?

string char and bool are 3 data type of variable. bool use less memory space than other and have 2 only state true and false, char use only 1 byte and the max lenght is 1 character string is an array of char so it takes as much space as the character contained.

How do you cast a variable to a Boolean?

To explicitly convert a value to bool, use the (bool) or (boolean) casts. However, in most cases the cast is unnecessary, since a value will be automatically converted if an operator, function or control structure requires a bool argument.


2 Answers

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.

like image 115
Mike Seymour Avatar answered Sep 21 '22 09:09

Mike Seymour


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).

like image 30
Kerrek SB Avatar answered Sep 23 '22 09:09

Kerrek SB