1
votes

In c / c++, how does the ordering of variables with different data types effect the size of the code?

The example I have seen involves 4 structs each with 4 variables. The variables were of type int, char, float and BYTE; each of the structs had the same number of variables (i.e. 4) and were named the same in each struct. The only difference was the order of the variables.

I understand that integer, char and float have different sizes (i.e. int 4 bytes etc), but how does the layout of these types effect the code size.

Thanks in advance!

2
Do you mean the size of executable, or the size of the struct in memory? - Matt K
it is due to padding....structure are padded to optimize reading...since read is always 4 byte(32-bit system)...so it tries to optimize by adding some padding...you can remove padding by using #pragma macro(but better is to align your members so that the padding is as limited as possible)... - Navin Ilavarasan
@ mkb The example only said smallest code size? - user1167501
Thanks guy's, so does the same apply to the executable i.e. when declaring variables in the header? - user1167501
Sorry, I meant to ask if the same applies inside the declaration of a class. - user1167501

2 Answers

1
votes

Welcome to the wonderful world of Structure Padding.

0
votes

Without going into compiler-specific options for structure padding, the best advice is to put the larger elements at the front of the structure and work your way down. In your example I'd order them float, int, BYTE, and char.

Each type has a memory alignment that works best for it; this will be the size of the type, or larger. The compiler manages this for you so most of the time you don't need to worry about it, it will insert padding into the structure so that the next element is on its own optimal alignment. By going in order from largest to smallest you maximize the probability that the next element will already be on a boundary and won't need any padding.