What is the usage of enums in the C language?

In the C language, enums (enumerations) are used to define new data types with a set of finite possible values.

The syntax for defining an enum is as follows:

enum 枚举名 {
    枚举值1,
    枚举值2,
    ...
};

The enumeration name is a user-defined identifier used to declare an enumeration type, where the enumeration values can be any integer constant. By default, the enumeration values start from 0 and increase incrementally, but an initial value can also be manually specified.

Once an enumeration type is defined, it can be used to declare variables and assign enum values to those variables. For example:

enum Weekday {
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday
};

enum Weekday today;
today = Wednesday;

In the example above, an enum type called Weekday is defined, which includes five enum values from Monday to Friday. Then a variable named today is declared and assigned the enum value Wednesday.

An enumeration type can be used in a switch statement to easily handle a set of limited possible values. For example:

switch(today) {
    case Monday:
    case Tuesday:
    case Wednesday:
        printf("It's a weekday.");
        break;
    case Thursday:
    case Friday:
        printf("It's almost weekend.");
        break;
    default:
        printf("Invalid value.");
}

In the example above, different operations are performed based on the value of ‘today’. When the value of ‘today’ is Monday, Tuesday, or Wednesday, it outputs “It’s a weekday.” When the value is Thursday or Friday, it outputs “It’s almost weekend.” If the value does not match any of the enumerated values, it outputs “Invalid value.”

In short, enums in C language are used to define a set of finite possible values, creating a new data type for these values which can then be used to declare variables, assign values, and perform comparisons.

bannerAds