如何在 C 的初始值设定项中使用 static_assert?

How to use static_assert within an initializer in C?

信不信由你,我想在扩展为指定初始化程序的宏中使用 static_assert:

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

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

我想要来自 INIT(42) 的错误,但是取消注释 static_assert 是一个语法错误。 AFAIK static_assert 在语法上是一个声明。我如何在此示例中使用它?

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

...我自己也不确定自己是如何结束这种可憎的行为的。但是,嘿,它有效(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-友好版本(只是加然后减 1 所以数组有一个正大小):

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