c - 结构中的枚举

标签 c struct enums structure unions

我的 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/

相关文章:

Swift 编译错误 : 'case' label can only appear inside a 'switch' statement?

java - 流API : create empty map with keys from enum

c++ - OpenMP 循环数组访问中的错误共享

c - 如何用C语言实现 ' continuous call'语法糖?

selenium-webdriver - 需要一个字段作为 Rust 特征的一部分

c - 使用结构在学生列表中找到最大的平均值

组合三个半字节

c - 是什么导致段错误?

c - 结构体数组 - 哈希表

c# - .Net 中是否可以将整数枚举设置为任意值