Enumeration


An Enumeration is a user-defined data type that consists of a set of named values, called enumeration constants or enumerators. The compiler assigns each enumerator a unique integer value, starting with 0 and incrementing it by 1 for each subsequent enumerator.

To build an enum, use the enum keyword followed by the enumโ€™s name and a comma to separate the enum items.

The enum keyword declares enumerations by specifying the enumeration name and enclosing a list of enumerators in braces.

The syntax for defining an enum in C is as follows:

enum enum_name {
    enumerator1,
    enumerator2,
    // More enumerators
};

Hereโ€™s a brief explanation of each part:

  • enum: Firstly, this keyword is used to declare an enumeration.
  • enum_name: It is the name you choose to give to your enumeration type. A new data type emerges for declaring variables.
  • enumerator1, enumerator2, etc.: These are the named integral constants that represent the values of the enumeration. By default, the system assigns consecutive integer values starting from 0, but you can assign specific integer values to them if you want.

For instance:

The following code declares an enumeration named Weekdays with seven enumerators:

enum Weekdays {
  MONDAY,
  TUESDAY,
  WEDNESDAY,
  THURSDAY,
  FRIDAY,
  SATURDAY,
  SUNDAY
};

In this example, MONDAY is assigned the value 0, TUESDAY is assigned the value 1, and so on.

You can create variables of this enumeration type and assign values to it, like any other data type:

enum Weekdays today = MONDAY;
printf("Today is %d\n", today);

In this example, we create a variable named today of type Weekdays and assign it the value MONDAY. We then print the value of today, which will be 0.
Enumerations can be useful for making code more readable and self-documenting, especially when dealing with a limited set of possible values.


Change Values

As you may be aware, the first item in an enum has the value 0. The second has a value of one, and so on.

You may simply adjust the values to make them more meaningful:

#include <stdio.h> 

enum Level {
  L1 = 20,
  L2 = 40,
  L3 = 70
};
  
int main() {
  enum Level myVar = L2;
  printf("%d", myVar);
  
  return 0;
}

//Output 40

Noting that setting a value for one item will update the numbers for the following things accordingly:

#include <stdio.h>

enum Level {
  L1 = 5,
  L2, // Now 6
  L3 // Now 7
};
  
int main() {
  enum Level myVar = L2;
  printf("%d", myVar);
  
  return 0;
}

Enum in a Switch Statement

Switch statements frequently use enums to find matching values:

enum Level {
L1,
L2,
L3
};

int main() {
  enum Level myVar = L2;

  switch (myVar) {
    case 1:
  printf("L1");
      break;
    case 2:
      printf("L2");
      break;
    case 3:
  printf("L3");
      break;
  }
  return 0;
}