The enum in C defines a list of constants. We use it to give meaningful names to the possible values. In most cases the developer doesn’t need to know the exact values behind these names.
We can use the list like a data type and create variables of this type. They will accept values from the list that we created.
Note: C allows the assignment of integer values out of the list. For more details see Representation below.
enum TAG { constant_1, constant_2, ... } variable_1, variable_2... ;
The most common way to use enumerables is to specify a TAG and then use it to create variables with it.
Let’s group the days of the week in a single data type. We want to create variables, using the TAG WeekDay. Each variable could take any of the values Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday:
Let’s try this again, without a TAG. We will write a little less code, but we cannot create
new variables for week days below the first row.
The
next example is equivalent to the above:
enum {Monday, Tuesday, Wednsday, Thursday, Friday, Saturday, Sunday} today, tomorrow; today = Friday; tomorrow = Saturday; if(today == Saturday || today == Sunday) printf("Have some rest!"); else printf("You should go to work.");
For the compiler, the values in an enumerated list are integer constants. By default the value of the first is 0 and each following value is incremented by 1.
In the examples above the days of the week are represented with the constants:
Monday = 0
Tuesday = 1
Wednesday = 2
...
Sunday = 6
C allows us to give our constants specific values.
enum WeekDay {Monday = 1, Tuesday, Wednsday, Thursday, Friday, Saturday, Sunday = 6};
Now Monday has the value 1, Tuesday increments
to 2 and so on. We also give Sunday the value 6, so it will have the same value
as Saturday.
Now, the example above could be done with one check in the if:
if(today == Saturday) printf("Have some rest!"); else printf("You should go to work.");
Since the values are represented by ints, we can use them in any way we use an int variable. Here is one example:
if(today < Sunday) tomorrow = today + 1; else tomorrow = Monday;
enum in C uses the standard scope rules. This is one of the main reasons to prefer it over multiple #define directives (#define has file scope).
In the scope you need to ensure that:
enum in C:
Any program using enumerables could be written without them, but it is likely to worsen the code quality.