Enumeration (enum) in C

What is enumeration (enum) in C? How to use Enum in C? Let's find out with TipsMake.com.com!

What is enumeration (enum) in C ? How to use Enum in C ? Let's find out with TipsMake!

Picture 1 of Enumeration (enum) in C

What is Enum in C?

Enum is a special type, representing a group of constants (values ​​that cannot be changed).

To create an enum in C , use the enum keyword, followed by the name of the enum, and separate the enum items with a comma:

enum Level { LOW, MEDIUM, HIGH };

Note that the last item does not need a comma. You don't have to capitalize, but it's generally recommended.

Enum is an abbreviation for enumeration. It means 'to enumerate specifically'.

To access the enum, you must create a variable for it. Inside the method main(), specify the enum keyword, followed by the name of the emum ( Level), then the name of the enum variable ( myVar) in this example):

enum Level myVar;

Now that you have created an enum variable ( myVar), you can assign it a value.

The attached value must be one of the items inside emum ( LOW, MEDIUMor HIGH):

enum Level myVar = MEDIUM;

By default, the first item ( LOW) has value 0, the second item ( MEDIUM) has value 1.

Now if you try printing myVar, it will produce the result 1, representing MEDIUM:

#include enum Level { LOW, MEDIUM, HIGH }; int main() { // Tạo một biến enum và gắn cho nó một giá trị enum Level myVar = MEDIUM; // Print biến enum printf("%d", myVar); return 0; }

Change the values

As you know, the first item of the enum has value 0. The second item has value 1…

To make the values ​​more meaningful, you can easily change them:

#include enum Level { LOW = 25, MEDIUM = 50, HIGH = 75 }; int main() { enum Level myVar = MEDIUM; printf("%d", myVar); return 0; }

Note that if you assign a value to an item, the next item will update the corresponding number:

enum Level { LOW = 5, MEDIUM, // Now 6 HIGH // Now 7 };

Enum in a Switch command

Enum is often used in Switch commands to check corresponding values:

enum Level { LOW = 1, MEDIUM, HIGH }; int main() { enum Level myVar = MEDIUM; switch (myVar) { case 1: printf("Low Level"); break; case 2: printf("Medium level"); break; case 3: printf("High level"); break; } return 0; }

Why and when to use Enum in C?

  1. Enum in C is used to name constants. That makes the code easier to read and maintain.
  2. Use enum in C when you have immutable values ​​like date, color, tag set.
Update 17 October 2023
Category

System

Mac OS X

Hardware

Game

Tech info

Technology

Science

Life

Application

Electric

Program

Mobile