[英]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 编程背后的理念需要记住的几件事:
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.