简体   繁体   English

枚举的乐趣:在 C 中是否允许将变量定义为枚举类型,然后将变量初始化为枚举中不包含的值?

[英]Fun with enums: in C is it allowed to define a variable as an enum type, then initialize the variable to a value not contained in the enum?

In the following short sample of code, a variable is defined as a particular enum type, then initialized to a value not contained in that enum type.在以下简短的代码示例中,变量被定义为特定的枚举类型,然后初始化为该枚举类型中不包含的值。 Is that even allowed?这甚至允许吗? If so, is there any possible good reason for doing it?如果是这样,是否有任何可能的充分理由这样做? Thank you!谢谢!

typedef enum
{
  element_zero = 0;
  element_one = 1;
  element_two = 2;
} enum_triple;

typedef enum
{
  element_five = 5;
} enum_single;

enum_single return_value = (enum_single)element_zero;

Several things to remember about C and the philosophy behind C programming:关于 C 和 C 编程背后的理念需要记住的几件事:

  • It is a product of the early 1970s;它是 1970 年代初期的产品;
  • It was developed primarily to implement the Unix operating system;它的开发主要是为了实现 Unix 操作系统;
  • It eschews high-level abstractions in exchange for speed;它避开高级抽象以换取速度;
  • It assumes that the programmer always knows what he or she is doing;它假定程序员总是知道他或她在做什么;
  • It assumes that the programmer is in the best position to know whether any kind of bounds or range check needs to be performed, and is smart enough to write the code to perform that check;它假定程序员处于最佳状态,知道是否需要执行任何类型的边界或范围检查,并且足够聪明地编写代码来执行该检查;

Enumerations in C are a convenient way of denoting sets of values that aren't necessarily ordered, but that's about as far as it goes. C 中的枚举是表示不一定有序的值集的便捷方式,但仅此而已。 They aren't a high-level abstraction in C like they are in Java or C#.它们不是 C 中的高级抽象,就像它们在 Java 或 C# 中一样。 Enumeration constants are not tied to any specific enumeration type, and objects of enumeration type can take values outside of the set of enumeration constants defined for them.枚举常量不依赖于任何特定的枚举类型,枚举类型的对象可以采用为它们定义的枚举常量集之外的值。

They're more a notational convenience than anything else.它们比其他任何东西都更方便。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM