如何在C初始化程序中使用static_assert? [英] How to use static_assert within an initializer in C?
问题描述
相信与否,我想在一个扩展到指定初始值的宏中使用 static_assert
:
<$ (N)<42,太大),* / \
[(N) #define INIT(N)\
/ * static_assert )] =(N)
int数组[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}}。 b $ b
...我不确定自己是如何结束这种憎恶的。但是,嘿,它可以工作(对于 N> 0
)!
//一个struct声明是一个有效的地方,可以将static_assert放入
struct {_Static_assert((N)< 42,太大); }
//然后我们可以把这个声明放在一个复合文字中......
(struct {_Static_assert((N)< 42,too large);}){}
//但是我们不能用`,`把它扔掉:这会产生一个非常量表达式。
//所以让我们在结构中添加一个大小为N的数组...
(struct {_Static_assert((N)< 42,too large); char c [N];}) {{0}}
//通过sizeof再次撬出N!
sizeof((struct {_Static_assert((N)< 42,too large); char c [N];}){{0}} c)
Believe it or not, I want to use I want an error from ... I'm not sure myself how I ended up with that abomination. But hey, it works (for
这篇关于如何在C初始化程序中使用static_assert?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! 0
-friendly version(只是加上然后减去 1 <
$ b $ $ p $ #define INIT(N)\
code $> [(N)] =(sizeof((struct {\
_Static_assert((N)<42,too large); \
char c [(N)+ 1]; \\ \\
}){{0}}。c) - 1)
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) };
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?#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
-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)