小编som*_*shy的帖子

使用复合文字对静态数组进行条件初始化

#include <stdint.h>\n\n#define INIT_UINT32 1\n#define INIT_INT32  2\n\n#define INIT INIT_INT32\n\ntypedef union\n{\n  uint32_t a;\n  int32_t  b;\n} Foo_t;\n\n/* Why does this compile... */\nstatic Foo_t foo_static = INIT == INIT_INT32 ?\n    (Foo_t){ .a = UINT32_MAX} : (Foo_t){ .b = INT32_MAX };\n\n/* but this doesn't? */\nstatic Foo_t foo_static_array[] =\n{\n  INIT == INIT_INT32 ? (Foo_t){ .a = UINT32_MAX} : (Foo_t){ .b = INT32_MAX }\n};\n\nint main(void)\n{\n}\n
Run Code Online (Sandbox Code Playgroud)\n

编译时,使用复合文字的 foo_static 条件初始化成功,但使用复合文字的 foo_static_array 条件初始化失败。以下是编译错误。

\n
$ gcc test.c\ntest.c:4:21: error: initializer element is not constant\n    4 | #define INIT_INT32  2\n      | …
Run Code Online (Sandbox Code Playgroud)

c c99

3
推荐指数
1
解决办法
87
查看次数

标签 统计

c ×1

c99 ×1