C-ENUMS

Dev Frank
5 min readMay 29, 2024

--

Imagine you are a software developer tasked with writing a program to manage a fantasy role-playing game. In this game, characters can belong to different classes like warriors, mages, and archers. You need a way to represent these classes in your code.

Without Enums

Initially, you might use plain integers to represent each class:

#define WARRIOR 0
#define MAGE 1
#define ARCHER 2

int characterClass = WARRIOR;

While this works, it has drawbacks:

  • The code is less readable because 0, 1, and 2 are not meaningful on their own.
  • Mistakes are easy to make. Assigning characterClass = 3; doesn't make sense, but there's nothing to prevent it.

Wait ! Let’s take a step back to know what exactly this enum is all about.

In C, an enum (short for enumeration) is a user-defined data type that consists of a set of named integer constants, known as enumerators. It is a way to define variables that can only take one out of a small set of possible values. We could also say that, an enum is a unique type that defines a collection of constants (fixed, unchangeable values).

Enumerations make code more readable and maintainable by giving meaningful names to these values instead of using raw numbers.

This might not make sense to you now, but let’s look at this comprehensive explanation of how to use enums in C:

Defining an Enum

An enum is defined using the enum keyword followed by a name for the enumeration and a list of enumerator names enclosed in curly braces { }.

enum EnumName variableName = ENUMERATOR1;

Let’s take an Example

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

In this example, Day is the name of the enumeration, and SUNDAY, MONDAY, TUESDAY, etc., are the enumerators. By default, the values of the enumerators start from 0 and increment by 1 for each subsequent name. So SUNDAY is 0, MONDAY is 1, and so on.

Note: That a comma is not needed after the last item.

Using uppercase for enum items is not mandatory, but it is often considered good practice.

“Enum” is short for “enumeration,” which means “a specifically listed set.”

Assigning Custom Values

You can assign specific integer values to some or all of the enumerators.

enum Month {
JANUARY = 1,
FEBRUARY,
MARCH,
APRIL = 10,
MAY,
JUNE,
JULY,
AUGUST,
SEPTEMBER,
OCTOBER,
NOVEMBER,
DECEMBER
};

In this example:

  • JANUARY is explicitly set to 1.
  • FEBRUARY follows JANUARY and will be 2.
  • MARCH follows FEBRUARY and will be 3.
  • APRIL is explicitly set to 10.
  • MAY follows APRIL and will be 11, and so on.

Using Enums

Once defined, you can declare variables of the enumeration type:

enum Day today;
today = WEDNESDAY;

You can also use enums in switch-case statements for clearer and more readable code:

#include <stdio.h>

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

int main() {
enum Day today;
today = WEDNESDAY;

switch (today) {
case SUNDAY:
printf("It's Sunday.\n");
break;
case MONDAY:
printf("It's Monday.\n");
break;
case TUESDAY:
printf("It's Tuesday.\n");
break;
case WEDNESDAY:
printf("It's Wednesday.\n");
break;
case THURSDAY:
printf("It's Thursday.\n");
break;
case FRIDAY:
printf("It's Friday.\n");
break;
case SATURDAY:
printf("It's Saturday.\n");
break;
default:
printf("Invalid day.\n");
break;
}

return 0;
}

This code defines an enum for days of the week, sets the variable today to WEDNESDAY, and uses a switch statement to print the corresponding day.

MORE EXAMPLES EXPLAINING ENUMS IN C

Here are a few more examples to help illustrate how enums work in C through various programs.

Example 1: Traffic Light States

This program defines an enum for traffic light states and uses it to control traffic signals

#include <stdio.h>

enum TrafficLight {
RED,
YELLOW,
GREEN
};

void printLightState(enum TrafficLight light) {
switch (light) {
case RED:
printf("Stop! The light is red.\n");
break;
case YELLOW:
printf("Caution! The light is yellow.\n");
break;
case GREEN:
printf("Go! The light is green.\n");
break;
default:
printf("Invalid traffic light state.\n");
break;
}
}

int main() {
enum TrafficLight currentLight = RED;
printLightState(currentLight);

currentLight = YELLOW;
printLightState(currentLight);

currentLight = GREEN;
printLightState(currentLight);

return 0;
}

Example 2: Error Codes

This program defines an enum for error codes and uses it to handle different error situations.

#include <stdio.h>

enum ErrorCode {
SUCCESS,
ERROR_FILE_NOT_FOUND,
ERROR_ACCESS_DENIED,
ERROR_OUT_OF_MEMORY
};

void handleError(enum ErrorCode error) {
switch (error) {
case SUCCESS:
printf("Operation completed successfully.\n");
break;
case ERROR_FILE_NOT_FOUND:
printf("Error: File not found.\n");
break;
case ERROR_ACCESS_DENIED:
printf("Error: Access denied.\n");
break;
case ERROR_OUT_OF_MEMORY:
printf("Error: Out of memory.\n");
break;
default:
printf("Unknown error code.\n");
break;
}
}

int main() {
enum ErrorCode error = ERROR_FILE_NOT_FOUND;
handleError(error);

error = ERROR_ACCESS_DENIED;
handleError(error);

error = SUCCESS;
handleError(error);

return 0;
}

Example 3: Months of the Year

This program defines an enum for the months of the year and prints the number of days in each month.

#include <stdio.h>

enum Month {
JANUARY = 1,
FEBRUARY,
MARCH,
APRIL,
MAY,
JUNE,
JULY,
AUGUST,
SEPTEMBER,
OCTOBER,
NOVEMBER,
DECEMBER
};

int getDaysInMonth(enum Month month) {
switch (month) {
case JANUARY: case MARCH: case MAY: case JULY: case AUGUST: case OCTOBER: case DECEMBER:
return 31;
case APRIL: case JUNE: case SEPTEMBER: case NOVEMBER:
return 30;
case FEBRUARY:
return 28; // Simplified; does not account for leap years
default:
return 0; // Invalid month
}
}

int main() {
for (enum Month month = JANUARY; month <= DECEMBER; month++) {
printf("Month %d has %d days.\n", month, getDaysInMonth(month));
}
return 0;
}

Example 4: User Roles

This program defines an enum for user roles in a system and checks access permissions.

#include <stdio.h>

enum UserRole {
ADMIN,
EDITOR,
VIEWER
};

void checkPermissions(enum UserRole role) {
switch (role) {
case ADMIN:
printf("Admin: Full access granted.\n");
break;
case EDITOR:
printf("Editor: Edit access granted.\n");
break;
case VIEWER:
printf("Viewer: Read-only access granted.\n");
break;
default:
printf("Unknown role.\n");
break;
}
}

int main() {
enum UserRole userRole = EDITOR;
checkPermissions(userRole);

userRole = VIEWER;
checkPermissions(userRole);

userRole = ADMIN;
checkPermissions(userRole);

return 0;
}

These examples show how flexible enums in C are. They help manage different states, handle errors, and define roles or categories in a way that’s easy to understand and maintain.

Summary

  • An enum defines a set of named integer constants.
  • Enumerators default to starting at 0 and increment by 1.
  • Custom values can be assigned to enumerators.
  • Enums improve code readability and maintainability.
  • Use enums in switch-case statements for clearer logic.

--

--

Dev Frank

Passionate tech enthusiast, diving deep into the world of software engineering. Thrilled to share insights with the world. A Software engineering student.