Reputation: 499
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?
Upvotes: 10
Views: 10945
Reputation: 2787
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.
Upvotes: 2
Reputation: 9863
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.
Upvotes: 17