Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

What is Enum in C?

Last Updated on September 22, 2023 by Mayank Dham

Enum in C is a versatile data representation tool. Enumeration in C enable developers to assign symbolic names to integral values using a concise syntax, making code more readable and maintainable. In this article, we will look at the power of enums, their syntax nuances, and how they help you write more efficient and organized C code. Enums can help you improve your coding skills whether you are a beginner or an expert.

What is Enum in C language?

The enum in C is also known as the enumerated type. Enum in C is a user-defined data type that consists of integer values, and it provides meaningful names to these values. The use of an enum in C makes the program easy to understand and maintain. The enum is defined by using the enum keyword.

Syntax to define Enum in C language?

In C, an enum is defined using the ‘enum’ keyword, and its constants are separated from one another by commas. Enums may be defined using the following syntax:

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

In the syntax above, int const1 has the default value of 0, int const2 has the default value of 1, int const3 has the default value of 2, and so on. However, you may alter these default values once the enum is declared. Below is an example of an enum named fruits and how you can change the default values.

enum fruits{mango, apple, strawberry, papaya}; 

The default value of kiwi is 20, banana is 10, strawberry is 5, and Orange is 7. If we wish to alter these default values, we may follow the instructions below:

enum fruits{  
Kiwi=20,  
banana=10,  
strawberry=5,  
Orange=7,  
};  

Enumerated type declaration

As is common knowledge, while using the C programming language, we must declare variables of predefined types, such as int, float, char, etc. The variable of a user-defined data type, such as an enum, can also be declared. Let’s examine the process for declaring an enum type variable.

Let’s say we make the status-type enum as shown below:

enum status{false,true};  

We now build the status type variable:

enum status s; // creating a variable of the status type.  

We have declared the status-type variables’ in the aforementioned sentence.
The two statements above may be worded as follows to create a variable:

enum status{false,true} s;  

In this case, the default value of false will be equal to 0, and the value of true will be equal to 1.

Let’s create a simple program of an enum.

#include <stdio.h>  
 enum weekdays{Sunday=1, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday};  
 int main()  
{  
 enum weekdays w; // variable declaration of weekdays type  
 w=Monday; // assigning value of Monday to w.  
 printf("The value of w is %d",w);  
    return 0;  
}

Output

The value of w is 2

How To Use Enum in C?

Enums are used as constants, or when we just want a certain set of values for a variable. For instance, there can only be seven values in the weekdays enum since there are only seven days in a week. A variable, however, may only hold one value at a time. We can use enums in C for multiple purposes; some of the uses of enums are:

  • Constant values to be saved (e.g., weekdays, months, directions, colors in a rainbow)
  • In C for utilizing flags
  • When utilizing C’s switch-case statements

Example of Using Enum in Switch Case Statement

In this example, we’ll make an enum with the constants North, East, West, and South for each of the four directions. The result will then be printed dependent on the value of the variable for the enum directions when we use the switch case statements to switch between the direction elements.

#include <stdio.h>  
enum directions{North=1, South, East, West};  
int main(){
    enum directions d;
    d=South;
    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

 We are headed towards South

Example of Using Enum in C for Flags

By maintaining the values of integral constants at a power of 2, we may utilize an enum for flags in C. This will enable us to use the Bitwise OR (|) operator to select and combine two or more flags without their overlapping. Let’s have a look at the example below where we set three flags to operate with an image: Crop, Rotate, and Save.

#include <stdio.h>
enum designFlags{
    CROP = 1,
ROTATE = 2,
SAVE = 4
};
    int main() {
    int myExample = ROTATE | CROP;
    printf("%d", myExample);
    return 0;
}

Output

3

Interesting Points About Initialization of Enum in C

An enum type’s enum names may all have the same value. Let’s examine the illustration.

#include <stdio.h>  
int main(void) {  
  enum fruits{banana = 10, strawberry=0, kiwi=1};  
    printf("The value of banana is %d", banana);  
    printf("\nThe value of kiwi is %d", kiwi);  
  return 0;  
}

Output

The value of banana is 10
The value of kiwi is 1
  • The compiler will automatically give default values beginning at 0 to the enum names if we do not supply any values for them.
  • The values can be given to the enum names in any sequence, and the unassigned names will receive the preceding value plus one by default.
  • Enum name values must be integral constants; they cannot be of other kinds, such as string, float, etc.
  • If we define two enums with the same scope, then these two enums should have separate enum names else the compiler will produce an error. All enum names must be unique in their scope.

Let’s understand this scenario through an example.

#include <stdio.h>  
enum status{success, fail};  
enum boolen{breakdown,pass};  
int main(void) {  
    printf("The value of success is %d", success);  
  return 0;  
}

Output

The value of success is 0
  • An enumerated data type can also be defined in enumeration without a name.
#include <stdio.h>  
enum {success, fail} status;  
int main(void) {  
    status=success;  
    printf("The value of status is %d", status);  
    return 0;  
    }

Output

The value of status is 0

Enum in C vs. Macro

In C, named constants may also be defined using the macro, much like an enum. However, using an enum in C is recommended since it offers several benefits over using a macro. Two of the main advantages are:

  • Enums adheres to the previously established "scope" requirements (in the last point of the previous section).
  • Enum items may have values automatically assigned by the compiler. As a result, making the declaration is simpler.

Conclusion
You have learned everything there is to know about enumeration in C language in this article, including several ways to utilize them. You may register on our PrepBytes platform if you’re interested in learning more about the basics of C programming.

Frequently Asked Questions (FAQs)

Here are some of the frequently asked questions on enumeration in C.
Q1. What exactly is an enum in C?
An enum, short for enumeration, is a C language construct that allows you to define a set of symbolic names (constants) mapped to integral values. It provides a more intuitive way to work with numeric values, improving code readability and organization.

Q2. How do enums enhance code readability?
Enums assign descriptive names to numeric values, making it easier to understand the purpose of a constant in your code. Instead of using raw numbers, you use meaningful labels, improving the overall clarity and maintainability of your codebase.

Q3. Can enum values be assigned specific integer values?
Yes, you can assign specific integer values to enum constants. By default, the first constant is assigned the value 0, and subsequent constants increment by 1. However, you can explicitly assign values to enum constants to create custom mappings.

Q4. Are enums limited to integer constants?
Yes, enums in C are primarily used with integer constants. While you cannot directly use floating-point or string values in enums, you can still represent different states or options using integer constants and attach meaningful labels to them.

Q5. How do enums compare to preprocessor macros?
Enums offer advantages over preprocessor macros. Unlike macros, enums provide type safety, meaning they’re treated as distinct types by the compiler, reducing the chances of errors. Additionally, enums are more maintainable, as changes to values are reflected automatically throughout the codebase, unlike macros that need manual updating.

Leave a Reply

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