Extra 5% OFF Use Code: OL05
Free Shipping over ₹999

Enumerations

In C, an enumeration (or enum) is a user-defined data type that consists of a set of named integer constants. Enumerations help make code more readable by allowing you to use meaningful names instead of arbitrary numbers, especially when working with fixed sets of related values.

Declaring an Enumeration

The enum keyword is used to declare an enumeration type. You define an enum by specifying a list of constant names, and each name is automatically assigned an integer value starting from 0 (unless explicitly specified).

enum Days {
    SUNDAY,    // 0
    MONDAY,    // 1
    TUESDAY,   // 2
    WEDNESDAY, // 3
    THURSDAY,  // 4
    FRIDAY,    // 5
    SATURDAY   // 6
};

Using Enumeration in Code

Enumerations are often used in situations where you need a set of named integer constants. You can use the enumeration name (Days in this example) to declare variables of the enum type.

Example of Enumeration Usag

#include <stdio.h>

enum Days {
    SUNDAY,
    MONDAY,
    TUESDAY,
    WEDNESDAY,
    THURSDAY,
    FRIDAY,
    SATURDAY
};

int main() {
    enum Days today;

    today = MONDAY;

    // Check the value of today
    if (today == MONDAY) {
        printf("It's Monday!\n");
    } else {
        printf("It's not Monday.\n");
    }

    return 0;
}

Explanation:

  • today is a variable of type enum Days, and it is assigned MONDAY.
  • Using if (today == MONDAY), we can compare today with the enum value MONDAY.

Customizing Enumeration Values

By default, the values assigned to enum members start from 0 and increment by 1. You can, however, assign specific values to any of the enum members:

enum Status {
    SUCCESS = 1,
    FAILURE = -1,
    PENDING = 0
};

In this case:

  • SUCCESS has a value of 1
  • FAILURE has a value of -1
  • PENDING has a value of 0

Example of Custom Values in an Enum

#include <stdio.h>

enum Status {
    SUCCESS = 1,
    FAILURE = -1,
    PENDING = 0
};

int main() {
    enum Status currentStatus = FAILURE;

    if (currentStatus == FAILURE) {
        printf("Operation failed.\n");
    } else if (currentStatus == SUCCESS) {
        printf("Operation succeeded.\n");
    } else {
        printf("Operation is pending.\n");
    }

    return 0;
}

Summary

  • Enumerations provide a way to define named integer constants.
  • Default values start at 0 and increment by 1, but you can assign specific values to any enum members.
  • Usage: Enums are useful for making code more readable, especially when dealing with a set of related constants.

    Leave a Reply

    Your email address will not be published.

    Need Help?