While I'm sure there are exceptions, normally compilers insert just enough padding to satisfy alignment requirements, both for the fields within the structure and for the structure as a whole. C compilers are not allowed to re-order fields in a structure.
Different types can have different alignment requirements, the size of a type must be a multiple of it's alignment requirement. On most 64-bit systems, the standard C primitive types will have an alignment requirement equal to their size. Structures will normally have an alignment requirement equal to the highest alignment requirement of their members.
Structures must sometimes be padded to ensure that their members meet alignment requirements and that the size of the structure as a whole is a multiple of it's alignment requirement.
So lets look at your structures, plus a third structure.
struct A
{
uint32_t var1; //size 4, alignment 4, offset 0
uint32_t var2; //size 4, alignment 4, offset 4
uint32_t var3; //size 4, alignment 4, offset 8
uint32_t var4; //size 4, alignment 4, offset 12
uint32_t var5; //size 4, alignment 4, offset 16
};
All fields are of type uint32_t, which has a size of 4 and an alignment of 4. Consequently no padding is needed and the structure has an overall size of 20 bytes and overall alignment of 4 bytes.
struct B
{
uint32_t var1; //size 4, alignment 4, offset 0
uint32_t var2; //size 4, alignment 4, offset 4
uint32_t var3; //size 4, alignment 4, offset 8
//4 bytes of padding.
uint64_t var5; //size 8, alignment 8, offset 16
};
The first three fields have a size and alignment of 4, so they can be allocated without padding. However var5 has a size and alignment of 8, so it can't be allocated at offset 12. Padding must be inserted and var5 allocated at offset 16. The structure as a whole has a size of 24 and an alignment of 8.
struct C
{
uint32_t var1; //size 4, alignment 4, offset 0
uint32_t var2; //size 4, alignment 4, offset 4
uint64_t var3; //size 8, alignment 8, offset 8
uint32_t var5; //size 4, alignment 4, offset 16
//4 bytes of padding
};
In this case all the variables can be allocated to suitable offsets without inserting padding. However the total size of the structure must be a multiple of it's alignment requirement (otherwise arrays would break alignment), so the end of the structure has to be padded. Again the struture as a whole has a size of 24 and an alignment of 8.
Some compilers have mechanisms to override the normal packing of structures, for example the __attribute__((packed)) mentioned in another answer. However these features must be used with extreme caution as they can easily lead to alignment violations.
uint64_thas stricter requirements thanuint32_t. - EOF