计算机内存中的枚举

Enums in computer memory

引用维基百科关于 enumerated types 的文章将是这个问题的最佳开场白:

In other words, an enumerated type has values that are different from each other, and that can be compared and assigned, but which are not specified by the programmer as having any particular concrete representation in the computer's memory; compilers and interpreters can represent them arbitrarily.

虽然我理解枚举的定义和使用,但我还不能理解枚举和内存之间的相互作用——当一个枚举类型被声明时没有创建一个枚举的实例类型变量,类型定义是作为联合还是结构存储在内存中?上述维基摘录背后的含义是什么?

这意味着枚举常量不需要位于内存中。你不能拿走他们的地址。

这允许编译器将所有对枚举常量的引用替换为它们的实际值。例如代码:

enum { x = 123; }
int y = x;

可以像这样编译:

int y = 123;

When an enum type is declared without creating an instance of enum type variable, is the type definition stored in memory as a union or a structure?

在 C 中,类型主要是编译时构造;一旦程序被编译为机器代码,所有类型信息都会消失*。访问结构成员是 "access the memory n bytes past this pointer".

因此,如果编译器如上所示内联所有枚举,则编译后的代码中根本不存在枚举。

* 除了调试信息部分中的可选内容外,但通常只有调试器才能读取。

Wikipedia 摘录并没有专门讨论 C 的 enum 类型。 C 标准对 enum 的工作方式有一些特定要求。

枚举类型与 char 或某些有符号或无符号整数类型兼容。表示形式的选择取决于编译器,编译器必须记录其选择(实现定义),但类型必须能够表示枚举的所有值。

枚举常量的值默认从 0 开始,每个连续常量递增 1

enum foo {
    zero, // equal to 0
    one,  // equal to 1
    two   // equal to 2
};

无论 enum 类型本身与什么兼容,常量始终是 int 类型。 (如果常量是枚举类型会更有意义;由于历史原因,它们是 int 类型。)

您可以为部分或所有常量指定值 -- 这意味着这些值不一定不同:

enum bar {
    two = 2,
    deux = 2,
    zwei = 2,
    one = 1,
    dos  // implicitly equal to 2
};

定义枚举类型不会导致在 运行 时将任何内容存储在内存中。如果你定义一个枚举类型的对象,这个对象的值将被存储在内存中(除非它被优化掉),并且会占用 sizeof (enum whatever) 字节。它与任何其他类型的对象相同。

枚举常量被视为常量表达式。表达式 two 几乎等同于常量 2.

请注意,C++ 对于 enum 类型有一些不同的规则。你的问题是C,我就不细说了。