C enum
An enumeration (enum) is a set of named integer constants. It makes the code easy to read, because you use names like MONDAY instead of numbers like 1.
Define and use
#include <stdio.h>
enum Day { MON, TUE, WED, THU, FRI, SAT, SUN };
int main(void) {
enum Day today = WED;
printf("%d\n", today);
printf("%d\n", SUN);
return 0;
}
Output:
Output of the above program is
2
6
By default the first name is 0, and each next name is one more.
Custom values
#include <stdio.h>
enum Level { LOW = 1, MEDIUM = 5, HIGH = 10 };
int main(void) {
enum Level l = MEDIUM;
printf("%d\n", l);
return 0;
}
Output:
Output of the above program is
5
enum with switch
#include <stdio.h>
enum Color { RED, GREEN, BLUE };
int main(void) {
enum Color c = GREEN;
switch (c) {
case RED: printf("Stop\n"); break;
case GREEN: printf("Go\n"); break;
case BLUE: printf("Blue light\n"); break;
}
return 0;
}
Output:
Output of the above program is
Go
Note:
In C an enum value is really an int. The compiler does not stop you from storing a wrong number in the variable, so be careful.
Next: C Preprocessor and Macros.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |