What is an enumeration (enum) in C?
An Enumeration or enum, is a user-defined data structure in C. Enumerations allow users to assign names to integer constants. Let’s take a deeper look:
Example
In this example, we will be considering the days of the week from Sunday to Saturday to create an enumeration.
Here’s the syntax:
enum week_days = {Sun, Mon, Tue, Wed, Thu, Fri, Sat};
enum week_days day;
We’ve created an enumeration of the days of the week.
- The enum is declared within the variable
week_days - The variable
dayis an object of our enum type variable and can be used to store the associated integer constant of ourweek_dayselements
Since we did not assign specific integer values to each name ourselves, the compiler assigns values starting from 0.
Code
We will now be looking at different ways to use an enumeration.
1. Basic
#include<stdio.h>//Global enumenum week_days {Sun, Mon, Tue, Wed, Thu, Fri, Sat};// 0, 1, 2, 3, 4, 5, 6int main() {enum week_days today;today = Fri;printf("Today is the %dth day of the week!", today);return 0;}
2. Iterator
#include<stdio.h>enum week_days {Sun, Mon, Tue, Wed, Thu, Fri, Sat};int main() {int i;for(i = Sun; i <= Sat; i++)printf("%d\n", i);return 0;}
Keep in mind
Enumerations can make our code easy to read and comprehend. Let’s do a quick recap of what we’ve learned and discuss key enum functionalities:
-
enumassigns names to integer constants. -
If an integer is not associated with any name within the enum, the compilers will assign values starting from 0.
-
We can assign specific values ourselves as well. The names that we choose not to assign will automatically be assigned the value of its predecessor, + 1.
#include <stdio.h>enum assignment_example{just = 1, an, example = 4};int main() {printf("%d\n", an);//Expect '2' as an output as the predecessor on 'an' is//'just' with an assigned value of '1'return 0;}
Free Resources