Enum
giving meaningful names to not-meaningful numbers
Enumeration
Enumeration (aka Enum): User-defined data type for assigning names to constants, so the code becomes more legible.
We will use
UPPER_SNAKE_CASE
most of the time for enums.
enum week {
SUNDAY,
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY
};
/**
* SUNDAY corresponds to 0
* MONDAY corresponds to 1
* ...
* SATURDAY corresponds to 6
* /
Sample Code
#include <stdio.h>
enum week {
SUNDAY,
MONDAY = 0,
TUESDAY = 3
};
int main() {
printf("%d, %d, %d\n", sunday, monday, tuesday);
return 0;
}
Output:
0, 0, 3
You can also declare enum variables.
// creating an enum variable called `day` of type `week`
enum week {
SUNDAY,
MONDAY,
TUESDAY
} day;
/*--- OR ---*/
enum week {
SUNDAY,
MONDAY,
TUESDAY
};
enum week day;
Sample Code
#include <stdio.h>
enum week {
SUNDAY,
MONDAY = 3,
TUESDAY
};
int main() {
enum week day;
day = tuesday;
printf("%d\n", day);
return 0;
}
Output:
4
Enums are useful when we want to define multiple variables which can be grouped together.
Last updated