Understanding Enumerations (Enums) in C: Grouping Constants

Discover what an enum is in C, a special data type that allows you to create a group of constants with meaningful names. Learn how to enhance code readability by defining enums using the enum keyword, making it easier to work with related constant values, such as levels or categories.



C Enumeration (enum)

What is an Enum?

An enum (short for "enumeration") is a special data type in C that allows you to create a group of constants, or unchangeable values. It helps make your code more readable by giving meaningful names to these constants.

Creating an Enum

To create an enum, use the enum keyword followed by the name of the enum, and separate each item with a comma. Here’s how you can define an enum for levels:

Syntax

enum Level {
  LOW,
  MEDIUM,
  HIGH
};

Accessing the Enum

To use the enum you created, you need to define a variable of that enum type. You can do this inside the main() function:

Syntax

enum Level myVar;

Assigning a Value

Once you have declared your enum variable, you can assign it a value from the enum items:

Example

enum Level myVar = MEDIUM;

Output the Enum Value

When you print the variable myVar, it outputs the corresponding integer value. By default, the first item (LOW) is 0, the second (MEDIUM) is 1, and the third (HIGH) is 2:

Example

#include 

int main() {
  enum Level myVar = MEDIUM;
  printf("%d", myVar); // Outputs 1
  return 0;
}
Output

1

Changing Enum Values

You can also customize the values assigned to the items in an enum:

Example

enum Level {
  LOW = 25,
  MEDIUM = 50,
  HIGH = 75
};

Print the Updated Enum Value

If you print myVar again after changing the enum, it will show the new value:

Example

printf("%d", myVar); // Now outputs 50

Enums in a Switch Statement

Enums are often used in switch statements to manage different cases based on their values:

Example

#include 

enum Level {
  LOW = 1,
  MEDIUM,
  HIGH
};

int main() {
  enum Level myVar = MEDIUM;

  switch (myVar) {
    case LOW:
      printf("Low Level");
      break;
    case MEDIUM:
      printf("Medium Level");
      break;
    case HIGH:
      printf("High Level");
      break;
  }
  return 0;
}

Why Use Enums?

Enums help give descriptive names to constants, making your code clearer and easier to maintain. They are useful for values that do not change, such as:

  • Days of the week
  • Colors
  • Card suits in a deck
  • Levels of a game