top

Search

C Tutorial

.

UpGrad

C Tutorial

Enumeration (or enum) in C

What is Enum in C?

Enumeration (or enum) in C is primarily used to assign names to the integral constants. It is referred to as a user-defined data type enabling users to create a set of named constants called enumerators. The enumeration in C offers a simple way to represent a collection of related values as a distinct type. The assigned names to the constants enhance the program’s readability and maintainability.

Naming the integer values makes the whole program simple to decode and maintain by the same or another programmer. The size of enum in C is platform-specific and can differ based on the target architecture and compiler. 

Having understood what is enum in C, let’s check out its syntax.

Syntax to Define Enum in C

You can define an enum in C by using the ‘enum’ keyword. The constants are separated using the comma. Here’s the syntax for defining an enumeration in C:

enum enum_name{int_const-1, int_const-2, int_const-3, .... int_const-N};

As seen from the above syntax, the default value of int_const-1 is 0, int_const-2 is 1, and so forth. You can alter these default values during the enum declaration.

Here’s an example of an enum named languages and also illustrates how you can alter the default values.

enum languages{English, French, Spanish, Russian};

The default values for the constants are:

English=0, French=1, Spanish=2, and Russian=3.

To modify the default values, you can define the enum as below:

enum languages
{

English=4,
French=3,
Spanish=0,
Russian=2
};

Examples of Enum Declaration

The declaration of enums follows the ‘scope’ rules. To simplify the declaration, the compiler can automatically allocate values to enum elements.

Let’s look at various examples to understand the declaration of enumeration in C:

Example-1:

enum Subjects 
{
English = 2,
Geography = 4,
Mathematics = 7,
};

In the given example, we declare an enum called "Subjects" with three possible values, namely English, Geography, and Mathematics. Every value is explicitly assigned a unique integer value. These assigned values need not be sequential.

Example 2:

enum Studies 
{
Pre-primary = 1,
Primary,
Secondary,
Higher-secondary,
Undergraduate,
Postgraduate,
};

In the above example, we declare an enum named "Studies" with six possible values denoting the different levels of education. The first value, i.e., pre-primary, is set to 1. This value continues incrementing until the last value in the enum list.

Initialization of Enum values

Here’s an enum in C example that initializes enum values.

Example-1:

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

In the example provided above, we declare an enum named "Month" and initialise a variable named "thisMonth" with the value "JUNE". Each enum value is assigned with an integer, beginning from 1 for “JANUARY” and incrementing from there.

Example-2:

enum Weekday 
{
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY,
SUNDAY
};
enum Weekday today = WEDNESDAY;

In the shared example, we declare an enum named "Weekday". The variable “today” is initialised with the value “WEDNESDAY”. The enum values are integers beginning from 0 and incrementing by 1. So, the value of "MONDAY" will be 0.

Example 3:

enum CardinalDirections 
{
North = 5,
South = 3,
East = 1,
West = 4,
};
enum Cardinaldirections currentDirection = South;

In this example, we declare an enum named "CardinalDirections" and initialise a variable "currentDirection" with the value "South". Each enum value is assigned a non-sequential integer.

Enumerated Type Declaration to Create a Variable

You can declare a variable for an enum just like you do for the pre-defined data types like char, int, float, etc. The following syntax helps you to create a variable for enum.

enum condition (true, false); //declares the enum (default values are 1 for true and 0 for false)
enum condition e; //creates a variable of type condition

For example, we declare an enum type “condition”. So, as mentioned above, you can create a variable for the same. You can combine both these statements as below:

enum condition (true, false) e;

How to Create and Implement Enum in C Program

Since we learned how to define an enum and create variables, let’s go through a few examples to learn how to implement an enum.

Follow these steps to create and implement an enum in C:

i) Enum declaration:

Declare the enum type through the enum keyword, followed by the enum's name. Within the curly braces, list out the enum values (known as enumerators) and separate each of them by commas. Obligatorily, you can assign explicit values to the enumerators.

enum Season 
{
WINTER,
SPRING,
SUMMER,
AUTUMN
};

ii) Variables’ declaration:

Declare variables of the enum type to store values from the enum. These variables will hold specific enumerators. For example,

enum Season thisSeason;

iii) Assign Values:

Use the assignment operator (=) to assign a value from the enum to the declared variable. For example,

thisSeason = SPRING;

iv) Use enum variables

You can use the enum variables in a C program. The following example program uses a switch statement to undergo various actions depending on the value of the enum variable.

switch (thisSeason) 
{
case WINTER:
printf("It is winter season.\n");
break;
case SPRING:
printf("It is spring season.\n");
break;
case SUMMER:
printf("It is summer season.\n");
break;
case AUTUMN:
printf("It is autumn season.\n");
break;
default:
printf("Invalid season.\n");
break;
}

How To Use Enum in C?

The enums in C come in handy when you want a variable to hold only a specific collection of values. For instance, for months enum, only twelve values can exist.

A variable is capable of holding only one value at a time. However, you can use enum in C# and C for various purposes. Here are its use cases:

  • To store constant values (for example, directions, weekdays, months, etc.

  • For using switch-case statements in C

  • For using flags in C

Example of Using Enum in Switch Case Statement

The following example program creates an enum with four positions, i.e., Left, Right, Front, and Behind are declared as constants. The switch case statements switch between the direction elements and display the output according to the variable's value for the enum “position”.

#include <stdio.h>

enum position{Left=1, Right, Front, Behind};

int main()
{

enum position p;

p=Behind;

switch(p)
{
case Left:
printf("It is left position.");
break;

case Right:
printf("It is right position.");
break;

case Front:
printf("It is front position.");
break;

case Behind:
printf("It is behind position");
break;
}
return 0;
}

Output:

It is behind position

Example of Using Enum in C for Flags

You can use an enum in C for flags by maintaining the values of integral constants with a power of 2. Consequently, you can select and merge two or more flags without overlapping. This is possible using the Bitwise OR (|) operator.

The following program sets three flags, i.e., Write, Check, and Implement.

#include <stdio.h>

enum processFlags
{

Write = 1,
Check = 2,
Implement = 3
};

int main() 
{
int z = Check & Implement;
printf("%d", z);
return 0;
}

Output:

2

Let’s verify this output by manual calculation:

00000010 (Check = 2)

00000011 (Implement = 3)

The AND operation of the above two binary representations leads to 00000010, so output =2.

The C program’s output and our calculation are the same. So, you can use an enum in C for flags. You can also add custom flags.

Interesting Points About Initialization of Enum in C

Here are some notable facts about the initialization of enum in C.

1) Multiple enum names or elements can bear identical value. The following example shows two enum elements with a similar value.

#include <stdio.h>

enum Subjects{English = 1, Geography = 0, Mathematics = 1};

int main()
{

printf("%d, %d, %d", English, Geography, Mathematics);
return 0;
}

Output:

1, 0, 1

2) Enum elements can be initialized in any order. The unassigned elements will have the value as previous + 1. Here’s an example program:

#include <stdio.h>
enum weekdays {Sunday, Monday = 3, Tuesday, Wednesday = 5, Thursday, Friday, Saturday = 11};
int main()
{
printf("%d %d %d %d %d %d %d", Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday);
return 0;
}

Output:

0 3 4 5 6 7 11

3) If custom values are not assigned to enum elements, the compiler automatically assigns them default values beginning from 0. In the following example, the compiler assigns values to the months, starting from 0 for January.

#include <stdio.h>
enum Months{January, February, March, April, May, June, July, August, September, October, November, December};
int main()
{
enum Months mt = June;
printf("The enum value of June in Months is %d", mt);
return 0;
}

Output:

The enum value of June in Months is 5

4) Each enum constant or element must have a unique scope. An enum element can’t be a part of two different enums in the same C program. Otherwise, the compilation fails. Let’s look at an example.

#include <stdio.h>
enum Subjects{English, Mathematics, Physical Education, Music, Art & Craft};
enum Core_Subjects{English, Mathematics};
int main()
{
return 0;
}

5) Enum values should be integral constants within the range of feasible integers.

Enum in C vs. Macro

Enum

Macro

Enums help you to create a set of related values with type safety and improved readability.

Macros are preprocessor directives that perform textual substitution or define symbolic constants.

Commonly, enum constants are used to denote a set of related options or values.

Commonly, macros are used for code generation or simple substitutions.

Enum values are not substituted during the preprocessing stage. They hold their symbolic representation during runtime. 

Macros are substituted during the preprocessing stage. The compiler checks the substituted values.

Enums can be incorporated in switch statements to enhance code readability.

Macros can be implemented for conditional compilation. You can also use them to define functions, constants, or code snippets.

Enum offers less flexibility.

Macro offers more flexibility.

Conclusion

Enums provide meaningful names for the sets of related constants. Hence, they can enhance your code readability. Type safety, code clarity, code consistency, compiler support, and simplified implementation of switch statements are a few more benefits of using enumeration in C.

We hope this tutorial will help you o comprehend the concept of enumeration effectively.

Tutorials are one of the most effective approaches to getting acquainted with the basics of C programming. In addition, you can pursue upGrad’s Full Stack Software Development Bootcamp to unlock exciting career opportunities since full-stack developers are currently in high demand. Pursuing this course will help you to become an exceptional full-stack developer and grab a high-paying job in your software development career.

Enroll now to start the journey!

FAQs

1. What is a typedef enum in C?
The typedef keyword in C is used to create synonyms or aliases for a data type. When it’s combined with an enum, typedef enum in C allows you to define an enum type with a custom name. The ability to create a new type name for an enum makes it simpler to declare variables of the particular type.

2. Can an enum in C have a forward declaration?

Forward declaration of an enum in C is possible by providing the enum name without defining its constants. Consequently, you can declare variables of the particular enum type before defining the enum. Note that you can’t use the enum constants until the enum is entirely defined.

3. Can you convert an enum to a string in C?

C doesn’t support a built-in mechanism to directly transform an enum to a string. But, you can manually define an array of strings comparable to the enum values and then use the enum value as an index to access the relevant string.

4. Can you have enum constants with multiple flags in C?

You can combine and use the bitwise operators like AND (&) and OR (|) to check for multiple enum constants representing flags in C. Consequently, you can depict a set of boolean flags or options using a single enum variable.

Leave a Reply

Your email address will not be published. Required fields are marked *