Reputation: 1487
A bool
takes 1 byte in C++. But, why does a bool[8]
take 8 bytes instead of 1 byte?
One byte has enough space for 8 bits.
I compiled this with GCC using -Os
flag:
#include <iostream>
using namespace std;
class Foo
{
public:
bool m_bool[8];
};
int main ()
{
cout << "Size: " << sizeof(Foo) << " byte(s) " << endl;
return 0;
}
It returns "Size: 8 byte(s)".
Is there a way to optimize it?
Upvotes: 1
Views: 726
Reputation: 1695
Is there a way to optimize it?
You can do that using a so-called bit-field. Bit-field values cannot have their address taken.
Upvotes: 0
Reputation: 3351
The compiler has to allow for you to take the addresses of the individual bools, i.e. things like
Foo foo;
bool* p = &foo.m_bool[0];
bool* q = &foo.m_bool[1];
If the bools were packed what would p and q be?
Upvotes: 7
Reputation: 20620
"Is there a way to optimize it?"
Are you sure optimization would be beneficial? You could use enums as flags instead of bools to store them all in a byte.
How to use enums as flags in C++?
Upvotes: 0
Reputation: 18290
Since I didn't see it mentioned in the comments above, I'll mention a concept in response to "Is there a way to optimize it?" in case you haven't worked with it yet. It's called bitmasking, where you essentially use an int as a series of bits, and use the bitwise operators to evaluate individual bits in the integer.
In order to easily set the bits in the string appropriately, it is common to define some constants which are semantically named and set to values of powers of 2 (so that they only "flip" one bit. You can easily use the bitshift operator to make it obvious which bit is being flipped:
#define IS_ADMIN = 1<<0;
#defing CLEAR_CACHE = 1<<1;
Then you test for admin like this:
if(userSettings & IS_ADMIN) { ...
Here's a starting-point wiki article
Upvotes: 1
Reputation: 23868
First off bool is not guaranteed to be a size of 1. Second when you group 8 ones together why would you still expect the result to be 1?
8 x 1 = 8
Upvotes: 2