Usage of Enum in C Language

This article illustrates the usage of the enum keyword in the C language. 【Paid】 STM32 Embedded Resource Package

Used to define multiple constants simultaneously

An example of defining months using enum is as follows.

#include <stdio.h> enum week {Mon=1, Tue, Wed, Thu, Fri, Sat, Sun}; int main() { printf("%d", Tue); return 0; }

By defining Mon’s value as 1, Tue’s value is automatically defined as 2, Wed’s value as 3, and so on. If Mon=1 is not specified, Mon’s default value will be 0. For example:

enum color {red, blue, green, yellow}; // red's value defaults to 0

For cases where values are assigned starting from the middle, see the following example:

enum color {red, blue, green=5, yellow}; // red, blue, green, yellow's values are 0, 1, 5, 6 respectively

Used to limit the range of variable values

Sometimes enum is used to ensure the robustness of the program.

#include <stdio.h> enum Month {Jan=1, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec}; int main() { enum Month a = Feb; printf("%d", a); return 0; }

For example, in the above case, the value of the enum type a is limited to those 12 variables.

Definition methods for enum types

When defining enum, you can also declare variables:

enum Month {Jan=1, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec} a, b; // This declares two enum type variables a and b

After defining enum, you can declare variables:

enum Month {Jan=1, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec}; enum Month a = Feb;

Defining an anonymous enum variable:

enum {Jan=1, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec} a; // This allows only the use of variable a of this enum type, and no other enum types can be defined

Leave a Comment