What does static_assert do, and what would you use it for?

Static assert is used to make assertions at compile time. When the static assertion fails, the program simply doesn’t compile. This is useful in different situations, like, for example, if you implement some functionality by code that critically depends on unsigned int object having exactly 32 bits. You can put a static assert like this

static_assert(sizeof(unsigned int) * CHAR_BIT == 32);

in your code. On another platform, with differently sized unsigned int type the compilation will fail, thus drawing attention of the developer to the problematic portion of the code and advising them to re-implement or re-inspect it.

For another example, you might want to pass some integral value as a void * pointer to a function (a hack, but useful at times) and you want to make sure that the integral value will fit into the pointer

int i;

static_assert(sizeof(void *) >= sizeof i);
foo((void *) i);

You might want to asset that char type is signed

static_assert(CHAR_MIN < 0);

or that integral division with negative values rounds towards zero

static_assert(-5 / 2 == -2);

And so on.

Run-time assertions in many cases can be used instead of static assertions, but run-time assertions only work at run-time and only when control passes over the assertion. For this reason a failing run-time assertion may lay dormant, undetected for extended periods of time.

Of course, the expression in static assertion has to be a compile-time constant. It can’t be a run-time value. For run-time values you have no other choice but use the ordinary assert.

Leave a Comment