Enumeration (or enum) in C

Hello there, aspiring programmers! Today, we're going to dive into the wonderful world of enumerations in C. As your friendly neighborhood computer science teacher, I'm excited to guide you through this journey. So, grab your favorite beverage, get comfortable, and let's embark on this adventure together!

C - Enumeration (or enum)

What is Enumeration (or enum) in C?

Imagine you're organizing your closet. You might categorize your clothes into different types: shirts, pants, dresses, and so on. In C programming, an enumeration (or enum for short) is like creating a custom category for your code. It's a way to define a group of named constants, making your code more readable and organized.

Let's start with a simple example:

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

In this example, we've created an enum called Days. Each item in the enum (MONDAY, TUESDAY, etc.) is called an enumerator. By default, C assigns integer values to these enumerators, starting from 0. So MONDAY is 0, TUESDAY is 1, and so on.

Defining and Declaring an Enum Type

Now that we understand what an enum is, let's look at how to define and declare one:

enum Fruits {
    APPLE,
    BANANA,
    ORANGE,
    MANGO
};

int main() {
    enum Fruits favorite = MANGO;
    printf("My favorite fruit is number %d\n", favorite);
    return 0;
}

In this example, we've defined an enum called Fruits. Then, in our main function, we've declared a variable favorite of type enum Fruits and assigned it the value MANGO. When we print favorite, it will output 3, because MANGO is the fourth item in our enum (remember, we start counting from 0).

Enum Variable Declaration

There are a few ways to declare enum variables. Let's look at them:

enum Colors {RED, GREEN, BLUE};

// Method 1: Declare variable separately
enum Colors paint;
paint = GREEN;

// Method 2: Declare and initialize in one line
enum Colors sky = BLUE;

// Method 3: Use typedef for convenience
typedef enum {CIRCLE, SQUARE, TRIANGLE} Shape;
Shape myShape = TRIANGLE;

Each of these methods accomplishes the same goal: creating a variable of an enum type. Choose the one that feels most natural to you!

Change Enum Constants Values

By default, enum constants are assigned increasing integer values starting from 0. But what if we want to change these values? Good news! We can do that:

enum Months {
    JAN = 1,
    FEB,
    MAR,
    APR = 100,
    MAY,
    JUN
};

In this example, JAN is explicitly set to 1, so FEB will be 2 and MAR will be 3. Then APR is set to 100, so MAY will be 101 and JUN will be 102.

Enum in Switch Statements

Enums are particularly useful in switch statements. They make your code more readable and less error-prone. Let's look at an example:

enum Weekday {MON, TUE, WED, THU, FRI};

enum Weekday today = WED;

switch(today) {
    case MON:
        printf("It's Monday. Time to start the week!\n");
        break;
    case TUE:
        printf("It's Tuesday. Keep the momentum going!\n");
        break;
    case WED:
        printf("It's Wednesday. Halfway there!\n");
        break;
    case THU:
        printf("It's Thursday. The weekend is almost here!\n");
        break;
    case FRI:
        printf("It's Friday. Time to celebrate!\n");
        break;
    default:
        printf("It's the weekend! Enjoy!\n");
}

This switch statement is much clearer than if we had used integer values. It's immediately obvious what each case represents.

Examples of Enumeration (enum) Type

Let's look at a few more examples to solidify our understanding:

Example 1: Traffic Light

enum TrafficLight {
    RED,
    YELLOW,
    GREEN
};

enum TrafficLight light = YELLOW;

if (light == RED) {
    printf("Stop!\n");
} else if (light == YELLOW) {
    printf("Prepare to stop.\n");
} else if (light == GREEN) {
    printf("Go!\n");
}

Example 2: Playing Cards

enum Suit {HEARTS, DIAMONDS, CLUBS, SPADES};
enum Rank {ACE = 1, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING};

struct Card {
    enum Suit suit;
    enum Rank rank;
};

struct Card myCard = {HEARTS, QUEEN};

printf("My card is the %d of %d\n", myCard.rank, myCard.suit);

Applications of Enums

Enums have many practical applications in programming. Here are a few:

  1. State Machines: Enums can represent different states in a system.
  2. Menu Options: Enums can be used to represent choices in a menu.
  3. Error Codes: Different types of errors can be represented as enum values.
  4. Configuration Options: Enums can represent different configuration settings.

Here's a table summarizing some common enum methods:

Method Description Example
Declaration Declare an enum type enum Colors {RED, GREEN, BLUE};
Variable Creation Create a variable of enum type enum Colors paint = GREEN;
Value Assignment Assign specific values to enum constants enum Months {JAN = 1, FEB, MAR};
Typedef Create a type definition for an enum typedef enum {CIRCLE, SQUARE} Shape;
Switch Usage Use enum in a switch statement switch(shape) { case CIRCLE: ... }

And there you have it! You've now been introduced to the world of enumerations in C. Remember, enums are your friends. They help make your code more readable, organized, and less prone to errors. As you continue your programming journey, you'll find many situations where enums can make your life easier. Happy coding, and may your enums always be in order!

Credits: Image by storyset