x-macro conditional error - number comparison

104 views Asked by At

I would like to generate compile time error for X-macro for all X(a, b) where a > b

/* X(a, b) */
#define LIST \
    X(10, 20) \
    X(5,  20) \
    X(30, 20) \
    X(1,  20)

So, generate error for X(30, 20)

Is this possible in C?

EDIT: example usage For me, left number is for example sizeof of some large struct and right number is fixed space to store this struct. If the struct is bigger then available space, I need compiler to generate error.

//e.g.
X(sizeof(struct conf), 2*PAGE)
2

There are 2 answers

2
mtijanic On BEST ANSWER

Yes, here's a proof of concept:

#pragma push_macro("X")
#undef X
#define X(a,b) typedef int x[(a>b)?-1:1];
LIST
#pragma pop_macro("X")

So, we define X to define a type of array of ints, with either -1 or 1, depending whether a is greater than b. If it is, the array of -1 elements will cause an error.

If using C11, the typedef line can be done using static_assert(a<=b) from assert.h

2
2501 On

It is possible in C11 by using the _Static_assert keyword:

#define X( a , b )  _Static_assert( a <= b , "Error!" ) 

Note that expressions a and b must be constant.