【问题标题】:Enums in Structures结构中的枚举
【发布时间】:2019-02-07 10:49:58
【问题描述】:

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

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

我希望变量的数据类型取决于枚举的选择。例如:如果选择枚举“1”,则“a”应该是“int”,“2”代表浮点数等。

【问题讨论】:

  • 数据可以存储在union中。需要一个单独的变量来指示正在使用union 的哪个成员。

标签: c struct enums structure unions


【解决方案1】:

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

【讨论】:

  • 这是对各种语言版本的支持的一个很好的介绍。
  • 感谢您的详细回答。但是 T_UNKNOWN 有什么用?这两个变量可以命名相同(而不是 v_int 和 v_float); struct list l1 = { .type = T_INT, .v = -937 }; struct list l2 = { .type = T_FLOAT, .v= 1.234 };我希望发生这种情况
  • T_UNKNOWN 只占用值 0,因此 T_INT 为 1,T_FLOAT 为 2,根据要求。它还可以用作默认初始化程序,指示尚未设置类型。不,您不能对v_intv_float 使用相同的名称;不同类型的名称必须不同。
猜你喜欢
  • 2017-06-14
  • 2021-09-26
  • 2021-06-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多