我的 C 文件中有一个结构和一个枚举。
struct list{
enum {1 , 2 ,3, 4};
//defining a variable 'a'
};
我希望变量的数据类型取决于枚举的选择。例如:如果选择枚举“1”,则“a”应为“int”,“2”表示 float 等。
最佳答案
您需要修复枚举
;你不能定义这样的数字列表。
那么您可能会使用 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 和匿名 union ,则需要为该 union 命名:
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
成员。
union 通常使用非常短的(单个字母)名称;它在代码中并不有趣,但在 C11 之前是必需的。
关于c - 结构中的枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52131802/