Defining an enum type
What you'll learn: How to create a custom data type that represents a set of named integer constants to make your code more readable.
The problem with magic numbers
Imagine you are writing a program for a traffic light. You could use the number 0 for Red, 1 for Yellow, and 2 for Green. While this works, your code will soon be filled with lines like if (status == 0). A week later, you might forget if 0 meant Red or if it meant "system off." These are called "magic numbers," and they make code hard to maintain.
Enter the Enumeration
An enumeration (or enum) is a user-defined type that allows you to assign names to numbers. Instead of remembering that 0 is Red, you can simply use the word RED. It makes your code read like a sentence rather than a math equation.
When you define an enum, C automatically assigns an integer value to each name, starting at 0 and incrementing by one for each subsequent item.
How to define an enum
To define an enum, use the enum keyword, followed by a name for your type (the tag), and a list of possible values inside curly braces.
#include <stdio.h>
// Defining the enum type
enum TrafficLight {
RED, // Assigned 0
YELLOW, // Assigned 1
GREEN // Assigned 2
};
int main() {
// Declaring a variable of our new enum type
enum TrafficLight officeLight;
// Assigning a value using the name, not the number
officeLight = RED;
if (officeLight == RED) {
printf("Stop! The light is red.\n");
}
return 0;
}
Why use this?
In the example above, RED is much easier to understand than 0. Under the hood, the computer still sees 0, but as a programmer, you get to work with meaningful words. This reduces bugs because you are less likely to accidentally assign an invalid number to a variable that should only represent a specific set of colors or states.
Key takeaway
Use enum to create a list of named constants that replace confusing numbers with descriptive words.