作者:郭彦伶克瑞雅书 | 来源:互联网 | 2022-12-05 21:23
我的C文件有一个结构和一个枚举.
struct list{
enum {1 , 2 ,3, 4};
//defining a variable 'a'
};
我希望变量的数据类型取决于枚举的选择.例如:如果选择枚举'1','a'应为'int','2'为float等.
1> Jonathan Lef..:
你需要修理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,那么你只能初始化union的第一个元素,即v_int
成员.
传统上使用非常短(单个字母)的名称进行结合; 它在代码中并不重要,但在C11之前它是必要的.