A class’s size can change simply by playing with the order of its members’ decla

A class’s size can change simply by playing with the order of its members’ declaration. For example:

 struct A{ bool a; int b; bool c;}; // sizeof (A) == 12

On my machine, sizeof (A) equals 12. This result might seem surprising because the total size of A’s members is only 6 bytes: 1+4+1 bytes. Where did the remaining six bytes come from? The compiler inserted three padding bytes after each bool member to make it align on a word boundary. You can reduce A’s size by reorganizing its data members as follows:

 struct B{ bool a; bool c; int b;}; // sizeof (B) == 8

This time, the compiler inserted only two padding bytes after the member c. Because b occupies four bytes, it naturally aligns on a word boundary without necessitating additional padding bytes.

As a rule, group data members are smaller than a word’s size together.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: