结构中的枚举

问题描述 投票:0回答:1

我的C文件有一个结构和一个枚举。

struct list{
    enum {1 , 2 ,3, 4};
    //defining a variable 'a'
};

我希望变量的数据类型取决于枚举的选择。例如:如果选择枚举'1','a'应为'int','2'为float等。

c struct enums structure unions
1个回答
5
投票

你需要修理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之前它是必要的。

© www.soinside.com 2019 - 2024. All rights reserved.