An enumeration(enum) is a special class that represents a group of constants. It is used to assign names to the integral constants, which makes a program easy to read and maintain.
The enum
keyword is used to create an enum. The constants declared inside are separated by commas.
By default, the first item in the list is assigned the value , the second item is assigned the value , and so on. The code below demonstrates this:
#include<stdio.h>enum color {red,green,blue};int main(){// Initializing a variable that will hold the enumsenum color current_color = red;printf("Value of red = %d \n", current_color);current_color = green;printf("Value of green = %d \n", current_color);current_color = blue;printf("Value of blue = %d \n", current_color);return 0;}
#include<stdio.h>enum suit {club = 0,diamonds = 10,hearts = 20,spades = 30};int main(){// Initializing a variable that will hold the enumsenum suit current_card = club;printf("Value of club = %d \n", current_card);current_card = hearts;printf("Value of hearts = %d \n", current_card);return 0;}
enum
is used for values that are not going to change (e.g., days of the week, colors in a rainbow, number of cards in a deck, etc.).
enum
is commonly used in switch-case statements. The code below shows an example:
#include <stdio.h>enum day {sunday , monday, tuesday,wednesday, thursday, friday, saturday};int main(){// Enums can also take their integer equivalent valuesenum day today = 4;switch(today){case sunday:printf("The day today is Sunday");break;case monday:printf("The day today is Monday");break;case tuesday:printf("The day today is Tuesday");break;case wednesday:printf("The day today is Wednesday");break;case thursday:printf("The day today is Thursday");break;case friday:printf("The day today is Friday");break;default:printf("The day today is Saturday");}return 0;}
Free Resources