Compile-time assertions in C
_Static_assert checks a constant expression while compiling, so bad builds fail early.
#include <limits.h>
#include <stdint.h>
typedef struct {
uint32_t id;
uint32_t flags;
} Header;
_Static_assert(sizeof(Header) == 8, "Header must stay eight bytes");
_Static_assert(CHAR_BIT == 8, "this code assumes octets");
_Static_assert(sizeof(int) >= 4, "int must hold a 32-bit value");
uint32_t header_id(const Header *h) {
return h->id;
}
How it works
- It takes a constant expression and a message.
- Layout and size assumptions are the usual subjects.
- There is no run-time cost at all.
Keywords and builtins used here
_Static_assertconstheader_idintreturnsizeofstructtypedefuint32_t
The run, in numbers
- Lines
- 15
- Characters to type
- 346
- Tokens
- 76
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 46 seconds.
Step 2 of 2 in Assertions, step 11 of 12 in Preprocessor & headers.