Wa0003.
Wa0003.
C Enums
An enum is a special type that represents a group of constants (unchangeable
values).
To create an enum, use the enum keyword, followed by the name of the enum,
and separate the enum items with a comma:
enum Level {
LOW,
MEDIUM,
HIGH
};
int main() {
// Create an enum variable and assign a value to it
enum Level myVar = MEDIUM;
// Print the enum variable
printf("%d", myVar);
return 0;
}
Change Values
As you know, the first item of an enum has the value 0. The second has the
value 1, and so on.
To make more sense of the values, you can easily change them:
enum Level {
LOW = 25,
MEDIUM = 50,
HIGH = 75
};
printf("%d", myVar); // Now outputs 50
Note that if you assign a value to one specific item, the next items will update
their numbers accordingly:
enum Level {
LOW = 5,
MEDIUM, // Now 6
HIGH // Now 7
};
enum Level {
LOW = 1,
MEDIUM,
HIGH
};
int main() {
enum Level myVar = MEDIUM;
switch (myVar) {
case 1:
printf("Low Level");
break;
case 2:
printf("Medium level");
break;
case 3:
printf("High level");
break;
}
return 0;
}
Program:
// An example program to demonstrate working
// of enum in C
#include<stdio.h>
int main()
day = Wed;
printf("%d",day);
return 0;
Output:
2