C Tutorial

Enumerations in C - What Are They


Introduction

Enumerations, commonly referred to as `enums,` are a fundamental concept in C programming. They provide a way to create custom data types that consist of a finite set of named values. Enumerations are especially useful when you need to represent a collection of related constants or options. In this guide, we'll explore what enums are in C and provide sample code to illustrate their usage.

What is an Enumeration?

An enumeration in C is a user-defined data type that consists of a set of named integer values. These named values are referred to as `enumerators` and provide a convenient way to represent a finite set of related constants or options. Enums make the code more readable and maintainable by assigning meaningful names to values.

Declaring Enumerations

Here's how you declare an enumeration in C:

#include <stdio.h> // Declare an enumeration named 'Days' enum Days { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday }; int main() { // Declare a variable of type 'Days' enum Days today; // Assign a value from the enumeration today = Wednesday; // Print the day printf(`Today is: %d\n`, today); return 0; }

In this example, we declare an enumeration named Days with seven enumerators representing the days of the week. We then declare a variable today of type Days and assign it the value Wednesday. When we print the value of today, it will display 2 since enumerators start from 0.

Assigning Values to Enumerators

You can explicitly assign values to enum enumerators:

#include <stdio.h> // Declare an enumeration with assigned values enum Months { January = 1, February = 2, March = 3, April = 4, May = 5, June = 6 }; int main() { // Declare a variable of type 'Months' enum Months currentMonth; // Assign a value from the enumeration currentMonth = March; // Print the month printf(`Current month: %d\n`, currentMonth); return 0; }

In this example, we declare an enumeration Months with assigned values starting from 1. We then declare a variable currentMonth and assign it the value March. When we print the value of currentMonth, it will display 3.

Conclusion

Enumerations in C provide a structured way to define sets of related constants, making code more readable and self-explanatory. This guide has introduced you to the basics of enumerations, including declaration, assigning values to enumerators, and their usage in C. As you continue your journey in C programming, you'll discover the utility of enums for representing various options, states, and more.

Written by Surfside Media

Senior Full Stack Developer specializing in Web Technologies.