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.)

0

3 Answers 3

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>.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

1
#include <assert.h>
//T should have size 10
static_assert(sizeof(T) == 10) 

It's available only the latest C compiler

1 Comment

Detail: _Static_assert available since C11. Latest C is C18

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.