Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C++ What's the point of using bool instead of char?

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?

like image 248
DarkPotatoKing Avatar asked Nov 03 '13 13:11

DarkPotatoKing


People also ask

What is the difference between char and bool?

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.

Why is bool not defined in C?

C does not have boolean data types, and normally uses integers for boolean testing. Zero is used to represent false, and One is used to represent true. For interpretation, Zero is interpreted as false and anything non-zero is interpreted as true.

Is bool smaller than char?

However, my C++ book (C++ Pocket Reference, O'Reilly) states: "The typical size of a bool is one byte," and "The size of a char is one byte. The size of a byte technically is implementation defined, but it is rarely anything but eight bits."

What does bool mean in C programming?

In C, Boolean is a data type that contains two types of values, i.e., 0 and 1. Basically, the bool type value represents two types of behavior, either true or false. Here, '0' represents false value, while '1' represents true value. In C Boolean, '0' is stored as 0, and another integer is stored as 1.


1 Answers

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.

like image 160
Dabbler Avatar answered Oct 02 '22 13:10

Dabbler