C / C ++: data on packaging or filling in the structure

I am using IDE Code :: Blocks with the GNU GCC compiler.

struct test { char a; char e; char f; char b; char d; }; 

sizeof(test) returns 5 .

I read this answer: Why is the sizeof size for the structure not equal to the sum of the sizeof of each member?

How is it that there is no indentation after the last char , so sizeof(test) returns 6 or 8 ? There are some more questions that I could ask by adding short and int , etc. But I think this question is good now. Would it be a complement to simplify the processor's work with the structure?

+8
c ++ c padding
source share
2 answers

Aligning a char is only 1, so there is no need for the structure to be padded to fulfill the larger alignment requirement.

+10
source share

Since in most cases you work with one member in time or pass the address of the structure, the compiler does not want to align the entire structure more than the alignment necessary for its members. This means that if you assign this structure (or pass it to a function), the processor will have to read it in a member. (and it will be a little slow).

+1
source share

All Articles