简体   繁体   中英

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:

  • It is a product of the early 1970s;
  • It was developed primarily to implement the Unix operating system;
  • 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. They aren't a high-level abstraction in C like they are in Java or 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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