Search code examples
structnestedpaddingmemory-alignmentpacking

C/C++ How Nested Structures Are Packed?


If a word is 4 bytes on my architecture, I would expect the following structure to be padded in order to be at least a word (4 bytes) in size.

// 4 bytes
struct
{
  uint8_t High : 4;
  uint8_t Low : 4;
} Value;

Now, let's say I have the following nested structure:

// ? bytes
struct
{
  uint8_t Address;
  struct
  {
    uint8_t High : 4;
    uint8_t Low : 4;
  } Value;
} Register;

How will this structure be packed? Will Value remain a word (4 bytes) in size? There are two ways I'm expecting this structure to be packed but I don't know which one is right or if even one is. Let's say R sand for Register, A is the member Address and V is the member Value. The two ways I can think of are:

First:

    Byte1 Byte2 Byte3 Byte4 Byte5 Byte6 Byte7 Byte8
R =     A     0     0     0     V     0     0     0

Second:

    Byte1 Byte2 Byte3 Byte4
R =     A     V     0     0

Thanks!


Solution

  • This structure is packed the following way:

        Byte1 Byte2 Byte3 Byte4
    R =     A     V     0     0