Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ sizeof with bool

It is a simple question. Code first.

struct A {
    int x; 
};
struct B {
    bool y;
};
struct C {
    int x;
    bool y;
};

In main function, I call

cout << " bool : " << sizeof(bool) <<
     "\n int : " << sizeof(int) <<
     "\n class A : " << sizeof(A) <<
     "\n class B : " << sizeof(B) <<
     "\n class C : " << sizeof(C) << "\n";

And the result is

bool : 1
int : 4
class A : 4
class B : 1
class C : 8

Why is the size of class C 8 instead of 5? Note that this is compiled with gcc in MINGW 4.7 / Windows 7 / 32 bit machine.

like image 934
Sungmin Avatar asked Oct 02 '12 01:10

Sungmin


2 Answers

The alignment of an aggregate is that of its strictest member (the member with the largest alignment requirement). In other words the size of the structure is a multiple of the alignment of its strictest (with the largest alignment requirement) member.

struct D
{
  bool a;
  // will be padded with char[7]
  double b; // the largest alignment requirement (8 bytes in my environment)
};

The size of the structure above will be 16 bytes because 16 is a multiple of 8. In your example the strictest type is int aligning to 4 bytes. That's why the structure is padded to have 8 bytes. I'll give you another example:

struct E
{
  int a;
  // padded with char[4]
  double b;
};

The size of the structure above is 16. 16 is multiple of 8 (alignment of double in my environment).

I wrote a blog post about memory alignment for more detailed explanation http://evpo.wordpress.com/2014/01/25/memory-alignment-of-structures-and-classes-in-c-2/

like image 198
evpo Avatar answered Oct 21 '22 22:10

evpo


Aligning structures to the size of a word, which is 4 bytes here.

like image 32
djechlin Avatar answered Oct 21 '22 23:10

djechlin