class CHaraICICCC
{
int i;
char c1;
int j;
char c2;
char c3;
char c4;
};
class CHaraIICCCC
{
int i;
int j;
char c1;
char c2;
char c3;
char c4;
};
void fun()
{
CHaraICICCC eici;
CHaraIICCCC eiicc;
int icic = sizeof(eici); // -> output of icic is 16.
int iicc = sizeof(eiicc); // -> output of icic is 12.
}
If any one knows, Please let me know why like this. Thanks Hara
Because of alignment. x86 compilers tend to align int types on 4 bytes boundary (for faster memory access) so CHaraICICCC would probably be laid out as this:
for a total of 15 bytes, while CHaraIICCCC would be:
for a total of 12 bytes (with no bytes wasted for padding). Of course, this is much compiler-related and dependant on your compilation options.
Stretching the question of "why" a little, I think I read somewhere that the reason for alignment is that it lets the CPU ignore bits of the data -- if your data is known to be 8-byte aligned, for example, the CPU can just ignore the 3 lower bits of the address, which improves efficiency. I could be wrong, but if I remember correctly, that's why CPUs require or prefer alignment.
With the default pack mode, on most architectures, members will be aligned at an offset (from the start of the structure) which is a multiple of their size.
If neccessary, padding bytes will be added to the structure to obtain that alignment.
So, assuming default packing and 4-byte integers, your first structure is really like this: