Search code examples
c++11alignmentstructuresizeofuint16

In C++11, why does int16_t have a size of 4 when declared after a float inside a struct?


I have a data structure like this:

struct mystruct
{
    float f;
    int16_t i;
};

sizeof(int16_t) gives 2, but sizeof(mystruct) gives 8 instead of 6. Why is that? How can I declare an int16_t variable of 2 bytes inside my data structure?


Solution

  • That is because of padding, given your system's architecture, the compiler adds some space to the structure.

    If you try to add another int16_t, you'll see that the size of this structure will still be 8.

    struct mystruct
    {
        float f;
        std::int16_t i;
        std::int16_t g;
    };
    

    In your original case

    struct mystruct
    {
        float f;
        std::int16_t i;
        //2 bytes padding
    };
    

    Note also that you can have padding in between members in the structure, that is why it is usually good advice to sort the members by decreasing order size, to minimize padding.

    You can have a quick read at the corresponding wikipedia page, which is well written. http://en.wikipedia.org/wiki/Data_structure_alignment#Typical_alignment_of_C_structs_on_x86