Table of contents
1.
Introduction
2.
Declaration of Enum in C
2.1.
Sample Examples of Enum
3.
Why do we use Enums in C?
4.
Facts about the initialization of Enum in C
5.
Enum in C vs. Macro
6.
FAQs
7.
Key takeaways
Last Updated: Mar 27, 2024

Introduction to Enum

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

This blog will give a brief introduction to Enum in C. Sometimes you must have wondered that it would have been easy if you could define any data type of your choice so it would be easy to understand and learn the concept in a much better way. There is a solution to this problem. The solution is Enum or Enumeration, a special kind of data type that the user can define. Let us discuss Enum in detail with some sample examples.

An enumeration type (also known as the Enum) is a data type in C programming consisting of integral constants. The enum keyword is used to define enums.

enum array {a1, a2, ..., aN};

 

By default, a1 is 0, a2 is 1, and aN would be equal to N. We can also change the default values of enum elements during the declaration of the Enum.

Below is an example of an enum named cars. Here the default values of the constants are: 

BMW = 0, Mercedes-Benz = 1, Porsche = 2, Maserati = 3, However we can change the values of the constants as follows:

// Changing default values of enum constants
enum cars {
    BMW = 100,
    Mercedes-Benz = 101,
    Porsche = 102,
    Maserati = 103,
};

Also See, Sum of Digits in C and C Static Function.

Declaration of Enum in C

We can create a variable of enum type, like this:

enum bool {false, true};
enum bool flag;

 

Here we have created a variable flag of the type of enum bool. The false value is equal to 0, and the true value equals 1.

Sample Examples of Enum

Now that we know how to declare enum and enum variables let us look at some examples to understand this concept.

Example 1:

#include <stdio.h>

enum colors_in_a_rainbow
{
    Violet = 1,
    Indigo = 2,
    Blue = 3,
    Green = 4,
    Yellow = 5,
    Orange = 6,
    Red = 7
};

int main()
{
    // creating a color variable of enum colors_in_a_rainbow type
    enum colors_in_a_rainbow color;
    color = Violet;
    printf("Value of Violet is %d \n", color);
    color = Green;
    printf("The value of Green is %d", color);

    return 0;
}
You can also try this code with Online C Compiler
Run Code

 

Output:

The value of Violet is 1 
The value of Green is 4

In the above example, we have declared an enum named colors which starts from Violet. After that, we have initialized the value of every color. We have printed the value of Violet and Green i.e., 1 and 4, respectively.

 

Example 2:

In this example, we will see how we can use a for loop with enum variables.

#include <stdio.h>

enum week
{
    Monday = 1,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday,
    Sunday
};

int main()
{
    // creating a days variable of enum week type
    enum week days;
    days = Monday;
    for (int i = days; i <= Sunday; i++)
    {
        if (i < Sunday)
            printf("%d, ", i);
        else
            printf("%d", i);
    }

   return 0;
}
You can also try this code with Online C Compiler
Run Code

 

Output:

1, 2, 3, 4, 5, 7

In the above example, we have created an enum named days which starts from Monday. After that, we have initialized the value of Monday with 1. In the main function, we have defined a for loop that traverses whole enum days and prints their values one by one.

You can also read about the dynamic arrays in c, and  Tribonacci Series

Why do we use Enums in C?

Enums are used for constants or when we want a variable to contain only one set of values. Weekday's Enum, for example, can only have seven values since there are only seven days in a week. On the other hand, a variable can only store one value at a time. Enums can be used for a variety of reasons in C, including the following:

  • To keep track of constant values (e.g., weekdays, months, directions, colors in a rainbow)
  • To use flags in C,
  • In C, when using switch-case statements.

 

Example of Enum using a Switch case statement:

#include <stdio.h>

enum directions
{
	North,
	East,
	West,
	South
};

int main()
{

	enum directions current_direction;

	current_direction = East;

	switch (current_direction)
	{
		case North:
			printf("We are headed towards North");
			break;

		case East:
			printf("We are headed towards East");
			break;

		case West:
			printf("We are headed towards West");
			break;

		case South:
			printf("We are headed towards South");
			break;
	}

	return 0;
}
You can also try this code with Online C Compiler
Run Code

 

Output:

We are headed towards East

In the above example, we have created an enum named directions with the value of 4 directions. We have used the switch case statements to switch between the direction elements, and we have then printed the output based on the value of the variable of enum directions.

Also see,  Short int in C Programming

Facts about the initialization of Enum in C

1) Multiple enums can have the same values. 

For example, consider the code given below here both red and blue balls have the same value :

#include <stdio.h>

enum balls {red = 3, green = 2, blue = 3};

int main()
{
    printf("%d, %d, %d",red, green, blue);
    return 0;
}
You can also try this code with Online C Compiler
Run Code

 

Output:

3, 2, 3

 

2) If we don’t assign any values to the enum elements, then the compiler will automatically assign default values to the elements.

For example, consider the code given below; here, we have not given any specific values to the enum elements, but still, they have values starting from 0.

#include <stdio.h>

enum balls {red, green, blue};

int main()
{
    printf("%d, %d, %d",red, green, blue);
    return 0;
}
You can also try this code with Online C Compiler
Run Code

 

Output:

0, 1, 2

 

3) We can provide values to enum elements in any order. Any unassigned element will get the value of the previous element + 1.

For example, consider the code given below; here, we have not given any specific values to blue, but still, its value is four, i.e., the value of the previous element + 1.

#include <stdio.h>

enum balls {red = 5, green = 3, blue};

int main()
{
    printf("%d, %d, %d",red, green, blue);
    return 0;
}
You can also try this code with Online C Compiler
Run Code

 

Output:

5, 3, 4

 

4) All the values assigned to the enum elements should be in the range [INT_MIN, INT_MAX].

5) Each enum element should have a distinct scope. It means that an element cannot be a part of two separate enums in the same program since compilation would fail.

#include <stdio.h>

enum bikes {Bajaj, Suzuki, Hero, KTM};
enum luxury_bikes {ducati, BMW, Kawasaki, KTM};

int main()
{  
    return 0;
}
You can also try this code with Online C Compiler
Run Code

 

Output:

Compile error
error: redeclaration of 'KTM'
enum luxury_bikes {ducati, BMW, Kawasaki, KTM};

note: previous declaration 'bikes KTM'
enum bikes {Bajaj, Suzuki, Hero, KTM};

Enum in C vs. Macro

In C, we can use the macro to declare named constants in the same way we use Enum. However, in C, the usage of Enum is favored since it offers several advantages over the macro. Two of the most important benefits are:

  • Enums follow the previously discussed 'scope' requirements. 
  • Enum elements can be assigned values automatically by the compiler. As a result, the declaration becomes simpler.

FAQs

  1. What is a preprocessor?
    A preprocessor directive is a built-in predefined function or macro that functions as a directive to the compiler and is run before executing the actual C program.
     
  2. What are printf() and scanf() functions?
    The printf() function prints integer, character, float, and string data on the screen.
    The format specifiers are as follows:
    1. The format specifier %d is used to print an integer value.
    2. The format specifier %s is used to print a string.
    3. The format specifier %c is used to print a character value.
    4. The format specifier %f is used to print a floating-point value.
    The scanf() function is used to take input from the user.
     
  3. What are static variables and functions?
    Variables and functions defined with the keyword Static are called Static Variables and Static Functions. Variables defined with the Static keyword have a scope limited to the function in which they are declared.

Key takeaways

In this article, we have discussed enum in C language and we have also discussed the different ways in which we can use enum. I hope you must have gained some knowledge after reading this blog. 

Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. Enroll in our courses and refer to the mock test and problems; look at the interview experiences and interview bundle for placement preparations.

Do upvote our blog to help other ninjas grow.

Happy Learning!

Live masterclass