Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How a bool type variable is stored in memory? (C++)

Tags:

c++

boolean

bool test;

sizeof(test) = 1 if using VS 2010. Since every C++ data type must be addressable, the "test" bool variable is 8-bits(1 byte).

My question is that does the "test" variable really occupy 1 byte in memory?

Is there any implementation skill that can make the bool data type occupy only one bit? If yes, can you give me an example?

bool test1[32](in VS 2010), int test2(in VS 2010)

Do test1 and test2 occupy the same memory?

like image 314
Fihop Avatar asked Nov 01 '11 14:11

Fihop


1 Answers

Every element of test1 must be addressable. This implies that array test1 (that was created using bool test1[32]) takes at least 32 bytes (1 byte per element).

If you want multiple boolean values to be stored in a single variable, use std::bitset or std::vector<bool> (but be aware that the latter is not really a vector of bools, it is a specialization designed to save space).

IIRC, C++11 also defines std::dynamic_bitset.

like image 195
Alexandre C. Avatar answered Oct 10 '22 17:10

Alexandre C.