Enumeration (enum) in C
What is enumeration (enum) in C ? How to use Enum in C ? Let's find out with TipsMake!
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
, MEDIUM
or 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?
- Enum in C is used to name constants. That makes the code easier to read and maintain.
- Use enum in C when you have immutable values like date, color, tag set.
You should read it
- How to use Enum in TypeScript
- How to use Enum in PHP 8
- Attribute in C #
- Data type in C / C ++
- How will play Super Mario at 380,000 frames per second?
- 25 unexpected facts about orange sure you don't know
- What to do when Skype video doesn't work?
- Learn about Krita - Free alternative to GIMP
- How to view battery life on iOS 12
- Toshiba introduces a Core i3 touchscreen laptop
- New printing solution with Google Cloud Print
- Free antivirus software is better than the paid one