Enumeration or Enum in C is a special kind of data type defined by the user. It consists of constant integrals or integers that are given names by a user. The use of enum in C to name the integer values makes the entire program easy to learn, understand, and maintain by the same or even different programmer.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Syntax to Define Enum in C

An enum is defined by using the ‘enum’ keyword in C, and the use of a comma separates the constants within. The basic syntax of defining an enum is:

enum enum_name{int_const1, int_const2, int_const3, …. int_constN};

In the above syntax, the default value of int_const1 is 0, int_const2 is 1, int_const3 is 2, and so on. However, you can also change these default values while declaring the enum. Below is an example of an enum named cars and how you can change the default values.

enum cars{BMW, Ferrari, Jeep, Mercedes-Benz};

Here, the default values for the constants are:

BMW=0, Ferrari=1, Jeep=2, and Mercedes-Benz=3. However, to change the default values, you can define the enum as follows:

enum cars{

BMW=3,

Ferrari=5,

Jeep=0,

Mercedes-Benz=1

};

Enumerated Type Declaration to Create a Variable

Similar to pre-defined data types like int and char, you can also declare a variable for enum and other user-defined data types. Here’s how to create a variable for enum.

enum condition (true, false); //declaring the enum

enum condition e; //creating a variable of type condition

Suppose we have declared an enum type named condition; we can create a variable for that data type as mentioned above. We can also converge both the statements and write them as:

enum condition (true, false) e;

For the above statement, the default value for true will be 1, and that for false will be 0.

How to Create and Implement Enum in C Program

Now that we know how to define an enum and create variables for it, let’s look at some examples to understand how to implement enum in C programs.

Also Read: Most Important Features of C Language You Must be Aware Of

Example 1: Printing the Values of Weekdays

#include <stdio.h>  

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

int main(){

    // printing the values of weekdays

    for(int i=Sunday;i<=Saturday;i++){

        printf("%d, ",i);

    }

    return 0;

}

Output:

Enum_in_C_1

In the above code, we declared an enum named days consisting of the name of the weekdays starting from Sunday. We then initialized the value of Sunday to be 1. This will assign the value for the other days as the previous value plus 1. To iterate through the enum and print the values of each day, we have created a for loop and initialized the value for i as Sunday.

Example 2: Assigning and Fetching Custom Values of Enum Elements

#include<stdio.h>

enum containers{

    cont1 = 5,

    cont2 = 7,

    cont3 = 3,

    cont4 = 8

};

int main(){ 

    // Initializing a variable to hold enums

    enum containers cur_cont = cont2;

printf("Value of cont2 is = %d \n", cur_cont);

cur_cont = cont3;

printf("Value of cont3 is = %d \n", cur_cont);

cur_cont = cont1;

printf("Value of hearts is = %d \n", cur_cont);

return 0;

}

Output:

Enum_in_C_2.

We have declared an enum named containers with four different containers as the elements in the above code. We have then given custom values to the elements and initialized the variable for the enum multiple times to print the relevant output.

How To Use Anum in C?

We use enums for constants, i.e., when we want a variable to have only a specific set of values. For instance, for weekdays enum, there can be only seven values as there are only seven days in a week. However, a variable can store only one value at a time. We can use enums in C for multiple purposes; some of the uses of enums are:

  • To store constant values (e.g., weekdays, months, directions, colors in a rainbow)
  • For using flags in C
  • While using switch-case statements in C

Example of Using Enum in Switch Case Statement

In this example, we will create an enum with all the 4 directions, North, East, West, and South as the constants. We will then use the switch case statements to switch between the direction elements and print the output based on the value of the variable for the enum directions.

#include <stdio.h>  

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

int main(){

    enum directions d;

    d=West;

    switch(d){  

        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;

}

Output:

Enum_in_C_3.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Example of Using Enum in C for Flags

We can use enum in C for flags by keeping the values of integral constants a power of 2. This will allow us to choose and combine two or more flags without overlapping with the help of the Bitwise OR (|) operator. Let’s consider the example below where we set three flags: Crop, Rotate, and Save to work with an image.

Example:

#include <stdio.h>

enum designFlags{

    CROP = 1,

ROTATE = 2,

SAVE = 4

};

int main() {

int myExample = ROTATE | SAVE;

printf("%d", myExample);

return 0;

}

Output:

Enum_in_C_4.

If we do the calculations for the above code, it is:

   00000010 (ROTATE = 2)

| 00000100 (SAVE = 4)

 ___________

   00000110 (Output = 6)

As you can see, our calculation and the output given by the program are the same. This concludes that we can use enum in C for flags. Also, we can add our custom flags.

Interesting Points About Initialization of Enum in C

There are a few facts about the enum worth noting, such as:

1. Multiple enum names or elements can have the same value. Here’s an example of two enum elements having a similar value.

Example:

#include <stdio.h>

enum Cars{Jeep = 1, BMW = 0, Mercedes_Benz = 0};

int main(){

    printf("%d, %d, %d", Jeep, BMW, Mercedes_Benz);

    return 0;

}

Output:

Enum_in_C_5

2. If we do not assign custom values to enum elements, the compiler will assign them default values starting from 0. For instance, the compiler will assign values to the months in the example below, with January being 0.

Example:

#include <stdio.h>

enum Months{January, February, March, April, May, June, July, August, September, October, November, December};

int main(){

enum Months m = May;

    printf("The Value of May in Months is %d", m);

return 0;

}

Output:

Enum_in_C_6

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

3. We can provide values to any elements of enum in any order. All the unassigned elements will get the value as previous + 1. The following program demonstrates the same.

Example:

#include <stdio.h>

enum weekdays {Sunday, Monday = 2, Tuesday, Wednesday = 6, Thursday, Friday = 9, Saturday = 12};

int main()

{

printf("%d %d %d %d %d %d %d", Sunday, Monday, Tuesday,

Wednesday, Thursday, Friday, Saturday);

return 0;

}

Output:

Enum_in_C_7

4. All the values assigned to the elements of enum must be an integral constant. For instance, they should be within the range of minimum and maximum possible integers.

5. All the enum elements or constants should have a unique scope. It means that an element cannot be a part of two different enums in the same program as it will fail during compilation. Here’s an example:

Example:

#include <stdio.h>

enum Cars{Mahindra, Jeep, BMW};

enum Luxury_Cars{BMW, Ferrari, Mercedes_Benz};

int main(){

    return 0;

}

Output:

Enum_in_C_8.

Enum in C vs. Macro

Similar to enum, you can also use the macro in C to define named constants. However, the use of enum in C is preferred as it has many advantages over the macro. Two of the key benefits are:

  • Enums follows the ‘scope’ rules as discussed earlier (in the last point of the previous section).
  • The compiler can automatically assign values to enum elements. Hence, the declaration becomes easier.

Conclusion

In this article, you have learned everything about enum in C and how to use it differently. If you want to know more about C programming fundamentals, you can sign up on our SkillUp platform. The platform offers free courses on multiple programming languages, including C and C++. You can take the opportunity to brush up on your C programming skills and put them to practice.

In today’s competitive world, full-stack developers are in higher demand than professionals with mastery in a particular language. Hence, it is of utmost importance to learn and master multiple programming languages. That’s exactly what our Full Stack Developer - MERN Stack is made for. The course provides tutorials and applied learning to get acquainted with 30+ programming skills and tools. Opt for the course to become the best and land a high-paying job in the software development field.

FAQs

1. What is an enum data type in C?

Enum, short for enumeration, is a user-defined data type in C programming. It enables developers to establish a collection of named constants, known as enumerators, each linked with an integer value. Enumerations provide a means to assign symbolic names to integral constants, greatly enhancing code readability and maintainability.

2. How do you define an enum in C?

To define an enum in C, you utilize the enum keyword followed by the designation of the enumeration. Within curly braces, enumerators, separated by commas, are listed. These enumerators represent the named constants associated with the enum. Each enumerator may optionally have an assigned value, typically starting from 0 and incrementing by 1 for subsequent enumerators unless explicitly specified otherwise.

3. How are enums used in C programming?

Enums are commonly used to represent a set of related constants with meaningful names. They significantly improve code readability by providing descriptive labels for integer values. Enums are frequently employed in switch-case statements, function parameters, and data structures to enhance program clarity and organization.

4. Can enums have specific integer values assigned to their elements?

Indeed, enums can possess explicitly assigned integer values for their elements. While the initial enumerator is assigned the value 0 by default, subsequent enumerators increment by 1. Nonetheless, developers retain the flexibility to assign values to individual enumerators directly, thus allowing for customized integer assignments.

5. What are the advantages of using enums over macros in C?

Enums offer notable advantages over macros. They ensure type safety, restricting enumerated values to a predefined set and mitigating potential errors. Moreover, enums enhance code readability and maintainability by providing symbolic representations of constants, contrasting with the textual substitution mechanism of macros.