Introduction
This blog will give a brief introduction to Enum in C. Sometimes you must have wondered that it would have been easy if you could define any data type of your choice so it would be easy to understand and learn the concept in a much better way. There is a solution to this problem. The solution is Enum or Enumeration, a special kind of data type that the user can define. Let us discuss Enum in detail with some sample examples.
An enumeration type (also known as the Enum) is a data type in C programming consisting of integral constants. The enum keyword is used to define enums.
enum array {a1, a2, ..., aN};
By default, a1 is 0, a2 is 1, and aN would be equal to N. We can also change the default values of enum elements during the declaration of the Enum.
Below is an example of an enum named cars. Here the default values of the constants are:
BMW = 0, Mercedes-Benz = 1, Porsche = 2, Maserati = 3, However we can change the values of the constants as follows:
// Changing default values of enum constants
enum cars {
BMW = 100,
Mercedes-Benz = 101,
Porsche = 102,
Maserati = 103,
};
Also See, Sum of Digits in C and C Static Function.
Declaration of Enum in C
We can create a variable of enum type, like this:
enum bool {false, true};
enum bool flag;
Here we have created a variable flag of the type of enum bool. The false value is equal to 0, and the true value equals 1.
Sample Examples of Enum
Now that we know how to declare enum and enum variables let us look at some examples to understand this concept.
Example 1:
#include <stdio.h>
enum colors_in_a_rainbow
{
Violet = 1,
Indigo = 2,
Blue = 3,
Green = 4,
Yellow = 5,
Orange = 6,
Red = 7
};
int main()
{
// creating a color variable of enum colors_in_a_rainbow type
enum colors_in_a_rainbow color;
color = Violet;
printf("Value of Violet is %d \n", color);
color = Green;
printf("The value of Green is %d", color);
return 0;
}
Output:
The value of Violet is 1
The value of Green is 4
In the above example, we have declared an enum named colors which starts from Violet. After that, we have initialized the value of every color. We have printed the value of Violet and Green i.e., 1 and 4, respectively.
Example 2:
In this example, we will see how we can use a for loop with enum variables.
#include <stdio.h>
enum week
{
Monday = 1,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday
};
int main()
{
// creating a days variable of enum week type
enum week days;
days = Monday;
for (int i = days; i <= Sunday; i++)
{
if (i < Sunday)
printf("%d, ", i);
else
printf("%d", i);
}
return 0;
}
Output:
1, 2, 3, 4, 5, 7
In the above example, we have created an enum named days which starts from Monday. After that, we have initialized the value of Monday with 1. In the main function, we have defined a for loop that traverses whole enum days and prints their values one by one.
You can also read about the dynamic arrays in c, and Tribonacci Series