Search code examples
cmacrosx-macros

x-macro conditional error - number comparison


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)

Solution

  • 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