Enumeration in C

In this tutorial, we will learn about enumeration in C. It helps give names to numbers using the enum keyword. This makes code easier to read and understand. For example, instead of using 0 for Sunday and 1 for Monday, you can use SUNDAY and MONDAY. This way, the code looks clear and makes fewer mistakes. Enumerations are useful when working with fixed values like days, colors, or directions.

Contents:

  1. What is Enumeration in C?
  2. Why Use Enumeration in C?
  3. Examples of Enumeration in C
  4. Enum with Structs in C
  5. Enum with Switch Statement in C
  6. Comparison Between Enum and #define Constants in C
  7. Advantages of Enumeration in C
  8. Limitations of Enumeration in C
  9. FAQs on Enumeration in C

What is Enumeration in C?

Enumeration (or enum) in C is a user-defined data type that consists of a set of named integer constants. It helps improve code readability, clarity, and maintainability by giving meaningful names to values.

Syntax:

enum enum_name {
    constant1,
    constant2,
    ...,
    constantN
};

By default, values start from 0 and increase by 1. You can also assign specific values.

advertisement

Example:

#include <stdio.h>
 
enum Weekday { SUN, MON, TUE, WED, THU, FRI, SAT };
 
int main() {
    enum Weekday today;
    today = WED;
 
    printf("Today is: %d\n", today); // Output: 3
 
    return 0;
}

This program defines an enum called Weekday, where days are numbered from 0 to 6. The variable today is set to WED, which has the value 3. The printf() function prints this value. Enums make code clearer by replacing numbers with readable names.

Free 30-Day C Certification Bootcamp is Live. Join Now!

Why Use Enumeration in C?

  • Improves Readability – Replaces confusing numbers with easy-to-understand names. This makes the code more readable.
  • Prevents Errors – Reduces mistakes caused by assigning the wrong number. Using names instead of numbers makes errors less likely.
  • Easy to Update – You can change a value in one place, and it updates everywhere in the program. This saves time and effort.
  • Automatic Numbering – By default, numbers start from 0 and increase by 1. You can also set specific values if needed.
  • Better for Switch Statements – Using named values in switch-case makes the code more structured and easier to follow.
  • Keeps Code Consistent – Ensures the same values are used throughout the program. This makes debugging and teamwork easier.
  • Removes Magic Numbers – No need to remember random numbers. Named values explain their purpose, reducing confusion.
  • Saves Memory – Uses only as much space as needed. Many compilers optimize enums to use minimal memory.
  • Stronger Type Safety – Helps catch mistakes at compile time. The compiler warns if an invalid value is used.
  • Better Debugging – When an error happens, names appear instead of numbers. This makes troubleshooting easier.

Examples of Enumeration in C

Example 1:

#include <stdio.h>
 
enum QuizResult { FAIL, PASS, DISTINCTION };
 
int main()
{
    enum QuizResult result;
    result = DISTINCTION;
 
    switch (result) {
        case FAIL:
            printf("Result: Fail. Better luck next time!\n");
            break;
        case PASS:
            printf("Result: Pass. Keep improving!\n");
            break;
        case DISTINCTION:
            printf("Result: Distinction. Excellent performance!\n");
            break;
    }
 
    return 0;
}

Output:

Result: Distinction. Excellent performance!

This program defines an enum called QuizResult, assigning values from 0 to 2. The variable result is set to DISTINCTION, which has the value 2. A switch statement checks the result and prints a message based on its value. Enums improve code readability by using meaningful names instead of numbers.

Example 2:

#include <stdio.h>
 
enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY };
 
int main() {
    enum Day today;
 
    today = FRIDAY;
 
    if (today == FRIDAY)
        printf("It's Friday! Weekend is near.\n");
 
    return 0;
}

Output:

It's Friday! Weekend is near.

This program defines an enum called Day, where days are assigned values from 0 to 6. The variable today is set to FRIDAY, which has the value 5. An if statement checks if today is FRIDAY and prints a message. Enums make code clearer by replacing numbers with readable names.

advertisement

Enum with Structs in C

In C, an enum (enumeration) is a user-defined type consisting of a set of named integer constants. When used inside a struct, it allows grouping meaningful values under a structured format, making the code more readable and organized.

Syntax:

enum EnumName { VALUE1, VALUE2, VALUE3 };
 
struct StructName {
    data_type member1;
    ...
    enum EnumName enumMember;
};

Example: Using enum with struct in C

#include <stdio.h>
 
// Define an enum for levels of access
enum AccessLevel { ADMIN, MODERATOR, USER };
 
// Define a struct that uses the enum
struct Account {
    char username[20];
    enum AccessLevel level;
};
 
int main() {
    struct Account a1 = {"Manish", ADMIN};
    struct Account a2 = {"Harshita", USER};
 
    printf("Username: %s, Access Level: %d\n", a1.username, a1.level);
    printf("Username: %s, Access Level: %d\n", a2.username, a2.level);
 
    return 0;
}

Output:

Username: Manish, Access Level: 0
Username: Harshita, Access Level: 2

This program uses an enum called AccessLevel to set user roles. A struct named Account stores a username and role. It creates two users: “Manish” as ADMIN and “Harshita” as USER. The program prints their names and roles. Enums make the code easy to read and avoid mistakes.

Enum with Switch Statement in C

Using an enum with a switch statement allows for more readable and maintainable code by replacing numeric constants with named constants.

Syntax:

enum EnumName { VALUE1, VALUE2, VALUE3 };
 
switch(enumVariable) {
    case VALUE1:
        // Code
        break;
    case VALUE2:
        // Code
        break;
    // ...
}

Example:

#include <stdio.h>
 
enum TrafficSignal { RED, YELLOW, GREEN };
 
void showSignalAction(enum TrafficSignal signal) {
    switch (signal) {
        case RED:
            printf("Stop the vehicle.\n");
            break;
        case YELLOW:
            printf("Slow down and prepare to stop.\n");
            break;
        case GREEN:
            printf("Go!\n");
            break;
        default:
            printf("Invalid signal.\n");
    }
}
 
int main() {
    enum TrafficSignal currentSignal = YELLOW;
    showSignalAction(currentSignal);
    return 0;
}

Output:

Slow down and prepare to stop.

This program uses an enum called TrafficSignal to represent traffic lights. The showSignalAction function checks the signal and prints the correct action. If the signal is RED, it says “Stop.” If YELLOW, it advises slowing down. If GREEN, it says “Go!” The program sets the signal to YELLOW and calls the function. Enums make the code clear and easy to manage.

Comparison Between Enum and #define Constants in C

Here’s the key differences between enum and #define constants in C:

Feature enum #define (Macro)
Definition Type Defines a set of integer constants. Defines constant values via preprocessor.
Syntax Check Type-checked by compiler. No type-checking; done by preprocessor.
Scope Limited to the scope of the enum block. Global scope (unless undefined).
Debugging Easier to debug (has symbolic names). Harder to debug (no symbolic names).
Memory Usage Uses memory (if assigned to a variable). No memory allocation (just substitution).
Grouping Groups related constants together. No grouping; each constant is defined separately.
Type Safety Yes, has a specific type (enum Color). No, treated as a raw number.
Code Readability Improves readability with named constants. Less readable compared to enum.
Automatic Numbering Yes, assigns values automatically. No, each value must be manually defined.
Expandable Yes, can be extended easily. No, requires manual updates.

Advantages of Enumeration in C

  • Easy to Read Code: Enums use clear names instead of numbers. This makes the code simple and easy to understand.
  • Prevents Mistakes: Enums make sure values belong to a set group. This helps avoid errors when assigning values.
  • Automatic Numbering: Enums give numbers to values starting from 0. This saves time and avoids mistakes.
  • Helps in Debugging: Debugging tools show enum names instead of numbers. This makes it easier to find and fix errors.
  • No Name Conflicts: Enum values stay within their group. This prevents name clashes with other variables.
  • Uses Less Memory: Enums store values as numbers. This makes them memory-friendly and fast.
  • Easy to Update: Enums keep values in one place. Changing an enum updates the value everywhere in the program.
  • Can Set Custom Values: You can assign specific numbers to enums. This is useful for matching fixed codes like error messages.

Limitations of Enumeration in C

  • Only Works with Integers: Enums can only store whole numbers. They cannot hold decimals, text, or characters.
  • No Strict Checking at Runtime: Enums help catch errors when compiling, but at runtime, any integer can still be assigned, even if it’s not in the enum list.
  • Risk of Name Conflicts: Enum names are not grouped unless you use unique prefixes (e.g., COLOR_RED, COLOR_BLUE). This can cause confusion in large programs.
  • No Automatic Text Conversion: Enums store numbers, but there is no built-in way to convert them to text. You must manually create a function to print names.
  • No Complex Values: Enums cannot use expressions, formulas, or function calls when defining values. Only fixed numbers are allowed.
  • Needs Full Definition: You cannot declare an enum before defining all its values. Unlike structures, partial declarations are not practical.
  • Not Ideal for Bitwise Operations: While enums can represent bit flags, C does not support them directly. You must manually assign bit values for bitwise operations.
  • Size Depends on Compiler: The memory used by an enum depends on the compiler and may vary across systems, affecting portability.

FAQs on Enumeration in C

1. What is an enum in C?
An enum is a user-defined data type that allows you to assign names to a set of integer constants. It makes programs easier to read and maintain.

2. What is the default value of enum constants?
By default, the first constant has a value of 0, and each subsequent constant increases by 1 automatically.

3. Can we assign custom values to enum constants?
Yes, you can manually assign specific integer values to enum constants as needed.

4. Are enum values limited to integers?
Yes, in C, enum values must be integers. You cannot use strings, characters, or floating-point values in an enum.

5. Can two enum constants have the same value?
Yes, it’s possible to assign the same value to multiple constants within an enum, though it may reduce clarity.

6. What is the size of an enum in C?
The size is generally the same as an integer, but it can vary depending on the system and compiler.

7. Can we use enums in switch statements?
Yes, enums work well with switch statements and help improve readability when checking different cases.

8. Are enums better than #define for constants?
Enums are usually better because they provide better grouping, debugging support, and limited type safety compared to simple macros.

Key Points to Remember

Here is the list of key points we need to remember about “Enumeration in C”.

  • Enums use clear names instead of numbers, making the code easy to read and understand.
  • Enum values start from 0 by default and increase by 1, but you can set custom values.
  • Enums help prevent errors because the compiler checks if values are valid.
  • Debugging is easier with enums since error messages show names instead of numbers.
  • Enums can only store whole numbers; they cannot hold text, decimals, or other types.
  • There is no built-in way to turn an enum into text, so you need to write a function for it.
  • If enum names are not unique, they may cause conflicts, so using prefixes like COLOR_RED helps.
  • Enums use little memory, but their size may vary depending on the compiler and system.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.