8
votes

sizeof(char) and sizeof(bool) are both equal to 1 (in my compiler/system/whatever, I've heard that it's not always the same value), a bool can only store true or false while a char can take more values and can act as multiple bool variables using bitwise operators (8 bits, each bit can be used as 1 bool for a total of 8 bools)

So is there any advantage on using bool instead of char?

So aside from readability is there anything else? I've read somewhere that int gets processed faster than short or byte even if takes more memory. Is there any difference in terms of speed between char and bool?

2
Yes: a bool can only store true or false.juanchopanza
Readability: using bool communicates that you intend to only store true or false. Also being precise with your types enables better error messages and better overload resolution.Alan Stokes
sizeof(bool) isn't necessarily 1, implementation may choose a bigger size.Yu Hao
If there was no bool you would ask why there is no bool and only char.Maroun
Well you could theoretically store 8 bools within one char if your system allows it. But intent is the main reason.RedX

2 Answers

16
votes

The main point of using bool is to express intent. If a variable is intended to store a value with true/false semantics, allowing for additional values is just a potential source of errors.

3
votes

bool is an abbreviation of "boolean", so every one familiar with boolean algebra can be sure that the variable might store only one of the two logical values (true or false): if you're need a variable that could be in only one of these two logical states, is there a reason to use something that could store anything else?

The only size, clearly defined by the standard is sizeof(char), it is 1 byte, but sizeof(bool) differs. What about 1 bit per value, it's about boolean vector template.

[taking an edit into attention]

You've profiled your application and found this to be a bottleneck? As I know, there's no advantages, except using boolean vectors if you're need to store and manipulate a couple of boolean variables.