Compile Time Checks

| 1 Comment

Here’s a handy macro you can use to do compile time checks:

#define CHECK__(line, x) typedef char check_##line##_[(x) ? 1 : -1];
#define CHECK_(line, x) CHECK__(line, x)
#define CHECK(x) CHECK_(__LINE__, (x))

You’ll get a compiler error if the check is false. Obviously the condition needs to be something the compiler can figure out at compile time. You might use it like this:

#pragma pack(push, 1)
struct x {
  uint8_t  a;
  uint32_t b;
#pragma pack(pop)

CHECK (sizeof (struct x) == 5)

I use it to check sizes of structures that have to match a protocol or format, for example, on disk structures that you know are supposed to be 512 bytes in size.

1 Comment

Wow - I didn't know you could do your own compile time checks. That's pretty neat.

Leave a comment