What is enum in C: Simple Explanation and Usage
enum (short for enumeration) is a user-defined type that consists of named integer constants. It helps make code more readable by giving meaningful names to sets of related values instead of using plain numbers.How It Works
Think of an enum as a list of named boxes, each holding a number. Instead of remembering numbers like 0, 1, or 2, you use names like RED, GREEN, and BLUE. This makes your code easier to understand, just like labeling jars in your kitchen instead of guessing what's inside.
When you create an enum, the compiler assigns integer values starting from 0 by default, but you can set your own numbers if you want. This way, you can group related values under one type and use them clearly in your program.
Example
This example shows how to define an enum for colors and use it in a program to print a color name based on its value.
#include <stdio.h> // Define an enum for colors enum Color { RED, // 0 GREEN, // 1 BLUE // 2 }; int main() { enum Color favorite = GREEN; if (favorite == RED) { printf("Favorite color is Red\n"); } else if (favorite == GREEN) { printf("Favorite color is Green\n"); } else if (favorite == BLUE) { printf("Favorite color is Blue\n"); } else { printf("Unknown color\n"); } return 0; }
When to Use
Use enum when you have a fixed set of related values that you want to name clearly. For example, days of the week, states of a game, or types of user roles. It helps avoid magic numbers in your code, making it easier to read and maintain.
Enums are especially useful in switch statements or when you want to restrict a variable to a limited set of options, improving code safety and clarity.
Key Points
- Enums assign names to integer constants for better readability.
- By default, values start at 0 and increase by 1.
- You can set custom values for enum members.
- Enums help prevent errors by limiting possible values.
- They improve code clarity and maintainability.