How to define and use enumeration types in C language?

In the C language, enumerations are used to define a set of constants of the same type. Here are the steps for defining and using enumeration types:

  1. Define an enumeration type:
    An enumeration type is defined using the keyword enum. The syntax is as follows:
  2. enum EnumTypeName {
    Constant1,
    Constant2,

    };
  3. The enumeration type name is a user-defined type name, constants are the values that the enumeration type can take, and constants are separated by commas.
  4. Declare an enumeration variable:
    An enumeration variable can be declared in places where an enumeration type is needed. The syntax is as follows:
  5. Declare a variable of the enumerated type named 枚举类型名.
  6. This declares an enumeration variable named “variable name”.
  7. To use enum constants:
    Enum constants can be accessed using the enum variable name followed by the constant name. The syntax is as follows:
  8. Enumeration variable name equals constant.
  9. Or alternatively:
  10. VariableName = EnumTypeName.Constant;
  11. In this way, the enumerated constants are assigned to the enumerated variable.

Here is a complete example:

#include <stdio.h>

// 定义枚举类型
enum Weekday {
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday,
    Sunday
};

int main() {
    // 声明枚举变量
    enum Weekday today;

    // 使用枚举变量
    today = Friday;

    // 输出枚举常量对应的值
    printf("Today is %d\n", today);

    return 0;
}

In the example above, a enum type “Weekday” is defined, with constants representing Monday through Sunday. In the main function, an enum variable “today” is declared and assigned the value “Friday”. Finally, the value of “today” is output, which is 4, indicating Friday.

bannerAds