简体   繁体   中英

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.

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/

将结构与单词的大小对齐,这里是4个字节。

Looking at the definition of your struct, you have 1 byte value followed by 4 byte Integer. This integer needs to be allocated on 4 byte boundary, which will force compiler to insert a 3 byte padding after your 1 byte bool. Which makes the size of struct to 8 byte. To avoid this you can change order of elements in the struct.

Also for two sizeof calls returning different values, are you sure you do not have a typo here and you are not taking size of pointer or different type or some integer variable.

Answered by Rohit J on struct size is different from typedef version?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM