Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is a char and a bool the same size in c++?

Tags:

c++

boolean

I'm reading The C++ Programming Language. In it Stroustrup states that sizeof(char) == 1 and 1 <= sizeof(bool). The specifics depend on the implementation. Why would such a simple value as a boolean take the same space as a char?

like image 227
108 Avatar asked Nov 05 '08 21:11

108


People also ask

What is the difference between char and bool?

Character refers to a single letter within a string (words). Boolean is either a True or False value.

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

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.


2 Answers

In modern computer architectures, a byte is the smallest addressable unit of memory. To pack multiple bits into a byte requires applying extra bit-shift operations. At the compiler level, it's a trade off of memory vs. speed requirements (and in high-performance software, those extra bit-shift operations can add up and slow down the application needlessly).

like image 60
Cybis Avatar answered Oct 03 '22 01:10

Cybis


Because in C++ you can take the address of a boolean and most machines cannot address individual bits.

like image 20
Robert Gamble Avatar answered Oct 03 '22 01:10

Robert Gamble