Building Better Code with Enum in C: Best Practices and Examples

Building Better Code with Enum in C: Best Practices and Examples

7 mins read542 Views Comment
Updated on Mar 2, 2023 17:23 IST

In C programming language, an enumeration (enum) is a user-defined data type that consists of a set of named constant values. Each value in the enum has an associated integer value, starting from 0 and incrementing by 1 for each subsequent value. Enums are commonly used to define a set of related values with distinct meanings.

2023_02_Enum-C-Programming.jpg

In C programming, an enumerated data type groups together constants. These named values refer to elements, members, enumerals, or enumerators. They are useful in designing large scale applications. In this article on enum in C, we will learn how to declare and initialize C enums in different ways. We will provide examples of various scenarios where enums are code applicable. We will be covering the following sections:

So, without further ado, let’s start! 

Introduction to Enum in C

In C, an enum (enumerated type) is a user-defined data type that consists of a set of named constants represented by integers. An enum declaration defines an enumerated type and specify its set of named constants. The named constants in an enum refer to as enumerators and represent distinct values within the enumerated type.

Enums provide a way to create descriptive, meaningful names for a set of integer values, making the code easier to read and maintain. They also help to reduce the possibility of using an incorrect constant value in the code. Because you can only use the defined enumerators.

You can declare enums and use just like any other data type in C. Once declared, variables of the enumerated type can be declared and assigned values from the set of named constants in the enum. Enums commonly represent sets of related values, such as the days of the week, the direction of a movement, or the status of a task.

Syntax

The syntax for declaring a static variable in C is below:

 
enum enum_name { enumerator_list };
Copy code

Where,

  • enum_name is the name of the enumerated type.
  • enumerator_list is a comma-separated list of enumerators, which are the named constants in the enumerated type.

For example, consider the following enumerated type declaration:

 
enum direction {
NORTH,
SOUTH,
EAST,
WEST
};
Copy code

In this example, the enumerated type direction is declared with four named constants: NORTH, EAST, SOUTH, and WEST. These named constants are represented by integers and are assigned values in the order they appear in the enumerator list. By default, the first enumerator is assigned the value 0, the second is assigned the value 1, and so on. 

However, you can also explicitly specify the values of the enumerators:

 
enum direction {
NORTH=10,
SOUTH=20,
EAST=30,
WEST=40
};
Copy code

In this example, the value of NORTH is explicitly set to 10, the value of SOUTH is set to 20, and so on.

Enumerated Type Declaration

To create a variable using an enumerated type in C, you first need to declare the enum. So, by declaring the enum, you can declare variables of the enumerated type and assign values to them from the set of named constants defined in the enum.

Here is an example of declaring an enum and creating a variable using the enum:

 
enum daysOfWeek {
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY,
SUNDAY
};
enum daysOfWeek today;
int main()
{
today = THURSDAY;
return 0;
}
Copy code

In this example, we declare an enum named daysOfWeek with the names of the days of the week as the named constants. We then declare a variable today of the daysOfWeek enumerated type, and assign it the value of THURSDAY. This makes it clear in the code what today represents, rather than using a plain integer value that may not be as easily interpretable.

Why Use Enums in C

Enums in C are necessary for several reasons:

  • Readability: Enums provide a way to give names to integer values, making the code more readable and self-explanatory. Instead of using integer literals, we can use meaningful names to represent specific values.
  • Maintenance: Enums can improve code maintainability by making it easier to understand the purpose of the integer values used in the code. In case of changes, it is easier to modify the enum constant names, rather than searching through the entire code for specific integer literals.
  • Type Safety: Enums are a user-defined data type. They help to ensure that the code uses only valid values. This type safety can prevent unintended bugs caused by using incorrect values.
  • Code Organization: Enums can help to group related constants together, making it easier to manage and organize the code. This is especially useful in large-scale applications that use many constants.

Overall, enums in C provide a way to improve code readability, maintainability, type safety, and organization, making the code easier to understand, maintain, and debug.

Creating and Implementing Enums in C

Example: 

 
#include <stdio.h>
enum direction {
NORTH,
EAST,
SOUTH,
WEST
};
int main()
{
enum direction heading = NORTH;
if (heading == NORTH)
printf("You are heading North\n");
else if (heading == EAST)
printf("You are heading East\n");
else if (heading == SOUTH)
printf("You are heading South\n");
else if (heading == WEST)
printf("You are heading West\n");
return 0;
}
Copy code

Output:

Output

In this example, we declare an enum named direction with four named constants: NORTH, SOUTH, EAST, and WEST. We then create a variable heading of the direction enumerated type and initialize it to NORTH. In the if statement, we use the named constants from the direction enum to check the value of heading and print out the corresponding direction. This makes the code more readable and understandable than if we were using integer values to represent the directions.

How are Enums Used in C?

Enums in C are necessary for constants, when a variable has a specific set of values. For example, in the case of weekdays, there can be only seven values as there are only seven days in a week. A variable can store only one value at a time. Enums have multiple uses in C, such as:

  • Storing constant values: Enums can store constant values like weekdays, months, directions, colors in a rainbow, etc.
  • Using flags: Enums have uses for flags in C.
  • Switch-case statements: Enums can help in switch-case statements in C.

Enums make the code more readable and organized, and they are a useful tool in C programming.

Using Enum in Switch Case Statement

Enums are in switch-case statements in C programming. In a switch-case statement, a variable is tested against a set of constant values, and the corresponding code is executed for the matching constant value. Using enums in switch-case statements makes the code more readable and organized.

Here is an example of using enums in a switch-case statement:

 
enum weekdays {
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday
};
int main() {
enum weekdays day = Monday;
switch(day) {
case Monday:
printf("Today is Monday\n");
break;
case Tuesday:
printf("Today is Tuesday\n");
break;
case Wednesday:
printf("Today is Wednesday\n");
break;
case Thursday:
printf("Today is Thursday\n");
break;
case Friday:
printf("Today is Friday\n");
break;
case Saturday:
printf("Today is Saturday\n");
break;
case Sunday:
printf("Today is Sunday\n");
break;
default:
printf("Invalid Day\n");
break;
}
return 0;
}
Copy code

In this example, an enum named weekdays is declared with constant values for each day of the week. A variable day is declared and initialized with Monday. The switch-case statement tests the day variable against each constant value in the weekdays enum. The corresponding code block is executed for the matching constant value. In this case, “Today is Monday” appears on the screen.

Using Enum in C for Flags

Enum has its use in C as flags, which represent the binary values, like 0 and 1, in a more readable way. The flags are applicable in many situations like setting or checking the options or settings in a software. For instance, the flags indicate the status of a file (e.g. read-only, hidden, archived). To use enums as flags, we need to define the enumerated values in such a way that each value has a unique power of 2.

Then, the combination of these values will represent multiple flags at the same time. For example, to represent three flags (read-only, hidden, archived), the enumerated values are 1, 2, and 4 respectively. Now, if we have to set all the flags for a file, we can set the value to 7 (1 + 2 + 4), and to unset a flag, we need to perform a bitwise operation on the value.

Here is an example of using enums as flags:

 
#include <stdio.h>
enum FileStatus
{
READ_ONLY = 1,
HIDDEN = 2,
ARCHIVED = 4
};
int main()
{
int file = READ_ONLY | ARCHIVED;
printf("File status: %d\n", file);
if (file & READ_ONLY)
printf("File is read-only.\n");
if (file & HIDDEN)
printf("File is hidden.\n");
if (file & ARCHIVED)
printf("File is archived.\n");
return 0;
}
Copy code

Output:

In this example, the enum FileStatus defines the different file status flags. The | operator sets multiple flags for the file variable. The & operator checks if a specific flag is set. 

Enums in C vs. Macros

Here is a table summarizing the differences between enums and macros in C programming:

Feature Enums Macros
Definition User-defined data type Preprocessor directive
Keyword enum #define
Type safety Yes No
Scope Limited to the block in which they are declared Global
Type of values Named constants Replaced by value

In general, enums are a better choice than macros for defining constants in C programming because they offer type safety and better control over the scope and visibility of the constants.

Endnotes

Hope this article was helpful for you to understand enums in C Programming. Learn more about C programming if you are new to it. If you want some hands-on guidance, check out all the top c programming courses.

Contributed by Prerna Singh

About the Author

This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio