1

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!

5
  • Do you mean the size of executable, or the size of the struct in memory?
    – Matt K
    Jan 24, 2012 at 17:03
  • 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)... Jan 24, 2012 at 17:15
  • @ mkb The example only said smallest code size? Jan 24, 2012 at 17:38
  • Thanks guy's, so does the same apply to the executable i.e. when declaring variables in the header? Jan 24, 2012 at 17:49
  • Sorry, I meant to ask if the same applies inside the declaration of a class. Jan 24, 2012 at 18:00

2 Answers 2

1

Welcome to the wonderful world of Structure Padding.

0

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.

2
  • Thanks Mark! I don't mean to sound stupid; because I now understand this relates to structs, but does this alignment of types also apply inside the declaration of a class i.e. effecting the size of the executable? Jan 24, 2012 at 18:04
  • @user1167501, the only difference between a struct and a class in C++ is the default access rights, public vs. private. The impact on executable size will be minimal in either case, the only time you'll notice is when you're creating a huge array of them and they'll only be part of the executable if they're static. Jan 24, 2012 at 18:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.