Search code examples
cstructsizeofmaintainability

How can I maintainably determine sizeof(struct ...)s?


Say I have a structure:

struct myStruct
{
    int a;
    short b;
    char c;
};

In Windows, MSDN states that int takes 4 bytes, short takes 2 bytes and char takes 1 byte. This totals up to 7 bytes.

I understand that most compilers will pad structures with an unspecified number of bytes to improve alignment. So, when I execute this program,

#include <stdio.h>

int main(void) {
    printf("%d\n", sizeof(struct myStruct));
    return 0;
}

I get an output of 8. This means 1 byte was padded.

Is there any way I can maintainably determine struct sizes in code (short of adding up individual sizeofs)?

I ask this because later, if I need to change my structure to include about fifteen elements more and if I add five more structures, all my struct sizeofs will change causing things to get messy.


Solution

  • You can enforce it:

    #define C_ASSERT(expr) extern char CAssertExtern[(expr)?1:-1]
    
    C_ASSERT(sizeof(struct myStruct) == 7); // or 8, whichever you want
    

    Whenever the size diverges from 7, the code will simply cease to compile.

    You can do similar things to enforce offsets of structure members. You'll need the offsetof() macro for that.