How to use static_assert within an initializer in C?

。_饼干妹妹 提交于 2019-12-12 05:52:53

问题


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)


来源:https://stackoverflow.com/questions/43661919/how-to-use-static-assert-within-an-initializer-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!