#include <stdint.h>
#define INIT_UINT32 1
#define INIT_INT32 2
#define INIT INIT_INT32
typedef union
{
uint32_t a;
int32_t b;
} Foo_t;
/* Why does this compile... */
static Foo_t foo_static = INIT == INIT_INT32 ?
(Foo_t){ .a = UINT32_MAX} : (Foo_t){ .b = INT32_MAX };
/* but this doesn't? */
static Foo_t foo_static_array[] =
{
INIT == INIT_INT32 ? (Foo_t){ .a = UINT32_MAX} : (Foo_t){ .b = INT32_MAX }
};
int main(void)
{
}
编译时,使用复合字面量对foo_static进行条件初始化成功,但使用复合字面量对foo_static_array进行条件初始化失败。以下是编译错误。
$ gcc test.c
test.c:4:21: error: initializer element is not constant
4 | #define INIT_INT32 2
| ^
test.c:6:14: note: in expansion of macro ‘INIT_INT32’
6 | #define INIT INIT_INT32
| ^~~~~~~~~~
test.c:21:3: note: in expansion of macro ‘INIT’
21 | INIT == INIT_INT32 ? (Foo_t){ .a = UINT32_MAX} : (Foo_t){ .b = INT32_MAX }
| ^~~~
test.c:4:21: note: (near initialization for ‘foo_static_array[0]’)
4 | #define INIT_INT32 2
| ^
test.c:6:14: note: in expansion of macro ‘INIT_INT32’
6 | #define INIT INIT_INT32
| ^~~~~~~~~~
test.c:21:3: note: in expansion of macro ‘INIT’
21 | INIT == INIT_INT32 ? (Foo_t){ .a = UINT32_MAX} : (Foo_t){ .b = INT32_MAX }
| ^~~~
有人能解释一下为什么会这样吗?
INIT == INIT_INT32
为真时,我本来期望选择带有.b = INT32_MAX
的初始化器。 - Ian Abbott