Enum is a user-defined data type that consists of the set of the name called enumerators. Enumeration is a user-defined data type. It is used to assign names to integral constants, it make a program easy to understand. ‘Enum’ keyword is used to define new enumeration types in the C programming language.
The enumerator names are usually identifiers that behave as constants in the language. A variable that has been declared as having an enumerated type can be assigned any of the enumerators as a value.
In other words, an enumerated type has values that are different from each other, and that can be compared and assigned, but which are not specified by the programmer as having any particular concrete representation in the computer’s memory; compilers and interpreters can represent them arbitrarily.
Syntax
enum type_name { value1, value2,...,valueN ...; };
Enum Variables can be defined in two ways. Here we provide an example for that.
enum week {sun, mon, tues}; enum color d1; or enum color {sun, mon, tues}d1;
Declaration of an enumerated variable
enum boolean { false; true; }; enum boolean check;
Different Examples of Enum
Example 1
#include <stdio.h> enum color { RED, GREEN=10, BLUE, YELLO, BLACK = 23, WHITE }; int main() { printf("\nRED = %d \nGREEN = %d \nBLUE = %d \nYELLO = %d \nBLACK = %d \nWHITE = %d ", RED, GREEN, BLUE, YELLO, BLACK, WHITE); }
Output
RED = 0 GREEN = 10 BLUE = 11 YELLO = 12 BLACK = 23 WHITE = 24
Example 2
#include <stdio.h> enum week { MON, TUES, WED, THURS, FRI, SATUR }; int main() { printf("\nMON = %d \nTUES = %d \nWED = %d \nTHURS = %d \nFRI = %d \n SATUR = %d ", MON, TUES, WED, THURS, FRI, SATUR); }
Output
MON = 0 TUES = 1 WED = 2 THURS = 3 FRI = 4 SATUR = 5
Example 3
We can also assign the character value to the variable. As shown below, here we have assign value ‘d’ to the variable ‘TUES’.
#include <stdio.h> enum week { MON, TUES = 'd', WED, THURS, FRI, SATUR }; int main() { printf("\nMON = %d \nTUES = %c \nWED = %d \nTHURS = %d \nFRI = %d \nSATUR = %d ", MON, TUES, WED, THURS, FRI, SATUR); }
Output
MON = 0 TUES = d WED = 101 THURS = 102 FRI = 103 SATUR = 104
Example 4
All enum variable must be unique in their scope. As shown in the below example we declare ‘WED’ variable with enum type w1 and enum type w2. When we compile this code it shows an error that we can not declare the same name variable with different enum types.
#include <stdio.h> enum w1 { MON, TUES, WED, }; enum w2 { WED, THURS, FRI, SATUR }; int main() { printf("\nMON = %d \nTUES = %d \nWED = %d \nTHURS = %d \nFRI = %d \nSATUR = %d ", MON, TUES, WED, THURS, FRI, SATUR); }
Output
main.c:3:11: error: redeclaration of enumerator 'WED' enum w2 { WED, THURS, FRI, SATUR }; ^~~ main.c:2:22: note: previous definition of 'WED' was here enum w1 { MON, TUES, WED, };