How to use static_assert within an initializer in

2019-08-19 00:48发布

问题:

Believe it or not, I want to use static_assert in a macro that expands to a designated initializer:

#define INIT(N) \
        /* static_assert((N) < 42, "too large"), */ \
        [(N)] = (N)

int array[99] = { INIT(1), INIT(2), INIT(42) };

I want an error from INIT(42), but uncommenting the static_assert is a syntax error. AFAIK static_assert is syntactically a declaration. How can I use it in this example?

回答1:

#define INIT(N) \
    [(N)] = (sizeof((struct {_Static_assert((N) < 42, "too large");char c[N];}){{0}}.c))

... I'm not sure myself how I ended up with that abomination. But hey, it works (for N > 0) !

// A struct declaration is a valid place to put a static_assert
        struct {_Static_assert((N) < 42, "too large");          }
// Then we can place that declaration in a compound literal...
       (struct {_Static_assert((N) < 42, "too large");          }){   }
// But we can't just throw it away with `,`: that would yield a non-constant expression.
// So let's add an array of size N to the struct...
       (struct {_Static_assert((N) < 42, "too large");char c[N];}){{0}}
// And pry N out again through sizeof!
sizeof((struct {_Static_assert((N) < 42, "too large");char c[N];}){{0}}.c)

0-friendly version (just adding then subtracting 1 so the array has a positive size):

#define INIT(N) \
    [(N)] = (sizeof((struct { \
        _Static_assert((N) < 42, "too large"); \
        char c[(N) + 1]; \
    }){{0}}.c) - 1)