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

mans picture mans · Oct 16, 2013 · Viewed 22.8k times · Source

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?

Answer

n. 'pronouns' m. picture n. 'pronouns' m. · Oct 16, 2013

You can check the size during compilation:

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

You need C++11 for that. Boost has a workaround for pre-c++11 compilers:

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

See the documentation.