Search code examples
c++data-structuresstatic-assert

How to check the size of a structure at compile time?


I want to add code that during compilation checks the size of a structure to make sure that it is a predefined size. For example I want to make sure that the size of this structure is 1024 byte when I am porting this code or when I am adding/removing items from structure during compile time:

#pack(1)
struct mystruct
{
    int item1;
    int item2[100];
    char item3[4];
    char item5;
    char padding[615];
 }

I know how to do this during run time by using a code such as this:

 if(sizeof(mystruct) != 1024)
 { 
     throw exception("Size is not correct");
 }

But it is a waste of processing if I do this during run time. I need to do this during compile time.

How can I do this during compilation?


Solution

  • Since C++11, you can check the size during compilation:

    static_assert (sizeof(mystruct) == 1024, "Size is not correct");
    

    Pre-c++11 compilers, Boost has a workaround:

    BOOST_STATIC_ASSERT_MSG(sizeof(mystruct) == 1024, "Size is not correct");
    

    See the documentation.