您需要修复enum;你不能定义这样的数字列表。
那么你可能会使用union。
struct list
{
enum { T_UNKNOWN, T_INT, T_FLOAT } type;
union
{
int v_int;
float v_float;
}; // C11 anonymous union
};
现在你可以定义:
struct list l1 = { .type = T_INT, .v_int = -937 };
struct list l2 = { .type = T_FLOAT, .v_float = 1.234 };
if (l1.type == l2.type)
…the values can be compared…
else
…the values can't be compared directly…
printf("l1.type = %d; l1.v_int = %d\n", l1.type, l1.v_int);
如果您没有可用的 C11 和匿名联合,则需要为联合命名:
struct list
{
enum { T_UNKNOWN, T_INT, T_FLOAT } type;
union
{
int v_int;
float v_float;
} u; // C99 or C90
};
假设 C99(所以你有指定的初始化程序),你可以使用:
struct list l1 = { .type = T_INT, .u = { .v_int = 1 } };
和
printf("l1.type = %d; l1.u.v_int = %d\n", l1.type, l1.u.v_int);
如果你没有 C99,那么你只能初始化联合的第一个元素,v_int 成员。
传统上使用非常短的(单字母)名称来表示工会;它在代码中并不有趣,但在 C11 之前它是必要的。