c 中的枚举?它们可以用于存储吗

enums in c? Can they be used for storing

我试图找出如果我在枚举中有 2 个变量会发生什么 我给它赋值。 我想了解我何时为 c_type 赋值,使用 C1 还是 C2?

我有以下代码:

typedef enum {
    C1 = 0,
    C2,
} c_type;

typedef struct A_a {
    c_type store;
} A;

FuncABC(int val)
{
    A a1;
    a1.store = val; /here store has C1 and C2, which one gets used here?
}

请告诉我。我知道上面的代码在 C 中逻辑上有效。 但是,想要澄清作业。

这是未定义的行为。您的代码最有可能导致崩溃,因为您取消引用了一个未初始化的指针。

您感到困惑的是 a1.store 将存储 C1C2

实际上a1.store可以是C1C223255val.

的值

回到 C 标准,enum 变量可以存储超出 enum 类型值范围的值。

你也可以参考这个Enumeration object set to a value not equal to any of its respective enumeration constants