Enum in C
Posted by Superadmin on October 26 2024 03:40:46

Enum in C

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.

Syntax

enum TAG { constant_1, constant_2, ...  } variable_1, variable_2... ;

Using enum in C

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:

Enum in C example - days of week

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.");

Representation

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};

    It is allowed to have multiple names with the same value. 

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; 

Scope and unique names

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:

Summary

enum in C:

    Any program using enumerables could be written without them, but it is likely to worsen the code quality.