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
  • 369,052
  • 73
  • 620
  • 1,021
Vitalyos
  • 1
  • 3

3 Answers3

4

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
  • 223,800
  • 12
  • 181
  • 301
3

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
  • 369,052
  • 73
  • 620
  • 1,021
0
#include <assert.h>
//T should have size 10
static_assert(sizeof(T) == 10) 

It's available only the latest C compiler

Hasee Amarathunga
  • 1,655
  • 11
  • 16