0

How to get C compile time #error if a sizeof(struct ...) not equal to a given number?

The question is from programming course, where I'd like to avoid to run miss-sized binary code.

(The sizeof operator, as we know, doesn't work in #if .. #endif directive.)

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Vitalyos
  • 1
  • 3

3 Answers3

5

How to get C compile time #error if a sizeof(struct ...) not equal to a given number?

You cannot, because the pre-processor knows nothing about sizes of types.

You can however static_assert:

static_assert(sizeof(T) == N, "T must have size N")

In C, the keyword is _Static_assert, also available through macro static_assert in <assert.h>.

eerorika
  • 232,697
  • 12
  • 197
  • 326
4

Don't. You already explained why.

In modern C++ you can write:

static_assert(sizeof(T) == 42);

Although it is better to write code that doesn't care what the size of T is.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
1
#include <assert.h>
//T should have size 10
static_assert(sizeof(T) == 10) 

It's available only the latest C compiler

Hasee Amarathunga
  • 1,901
  • 12
  • 17