Issue
Is there any way to use a sizeof
in a preprocessor macro?
For example, there have been a ton of situations over the years in which I wanted to do something like:
#if sizeof(someThing) != PAGE_SIZE
#error Data structure doesn't match page size
#endif
The exact thing I'm checking here is completely made up - the point is, I often like to put in these types of (size or alignment) compile-time checks to guard against someone modifying a data-structure which could misalign or re-size things which would break them.
Needless to say - I don't appear to be able to use a sizeof
in the manner described above.
Solution
There are several ways of doing this.
Following snippets will produce no code if sizeof(someThing)
equals PAGE_SIZE
; otherwise they will produce a compile-time error.
1. C11 way
Starting with C11 you can use static_assert
(requires #include <assert.h>
).
Usage:
static_assert(sizeof(someThing) == PAGE_SIZE, "Data structure doesn't match page size");
2. Custom macro
If you just want to get a compile-time error when sizeof(something)
is not what you expect, you can use following macro:
#define BUILD_BUG_ON(condition) ((void)sizeof(char[1 - 2*!!(condition)]))
Usage:
BUILD_BUG_ON( sizeof(someThing) != PAGE_SIZE );
This article explains in details why it works.
3. MS-specific
On Microsoft C++ compiler you can use C_ASSERT macro (requires #include <windows.h>
), which uses a trick similar to the one described in section 2.
Usage:
C_ASSERT(sizeof(someThing) == PAGE_SIZE);
Answered By - nevermind Answer Checked By - Cary Denson (WPSolving Admin)