Sometimes a variable can only have a small set of possible values.
For example, a day can be Monday, Tuesday, Wednesday, and so on. Instead of using numbers everywhere, C provides enumerations, or enum.
What is an Enumeration?
An enumeration is a user-defined type that consists of a set of named integer constants.
It is created using the enum keyword.
enum Day
{
MONDAY,
TUESDAY,
WEDNESDAY
};
Here, MONDAY, TUESDAY, and WEDNESDAY are enumeration constants.
By default, the first value is 0, the next is 1, and so on.
MONDAY → 0
TUESDAY → 1
WEDNESDAY → 2
Creating an Enum Variable
We can create a variable using the enumeration:
enum Day today;
today = TUESDAY;
We can then use it in the program:
printf("%d", today);
Output:
1
The names make the code easier to understand than using numbers directly.
Assigning Custom Values
We can also assign our own integer values:
enum Status
{
FAILED = 0,
PASSED = 1,
PENDING = 5
};
Now:
FAILED → 0
PASSED → 1
PENDING → 5
If you omit a value, numbering continues from the previous value.
Example
#include <stdio.h>
enum Day
{
MONDAY,
TUESDAY,
WEDNESDAY
};
int main()
{
enum Day today = TUESDAY;
if (today == TUESDAY)
{
printf("Today is Tuesday");
}
return 0;
}
Output:
Today is Tuesday
Why Use Enumerations?
Enums are useful when a variable has a fixed set of named choices.
For example:
Days of the week
Months
Traffic-light states
User roles
Program states
Error or status codes
They make programs more readable and easier to maintain.
Enum vs Constant
You can also create constants using #define:
#define RED 0
#define GREEN 1
#define BLUE 2
But an enum groups related named integer constants together:
enum Color
{
RED,
GREEN,
BLUE
};
This makes the relationship between the values clearer.
In Simple Words
An enumeration (
enum) lets us give meaningful names to a set of integer constants.
For example:
enum Color
{
RED,
GREEN,
BLUE
};
Instead of writing numbers like 0, 1, and 2, we can use meaningful names like RED, GREEN, and BLUE.