0
0
Cprogramming~5 mins

Enum declaration

Choose your learning style9 modes available
Introduction

An enum helps you give names to a set of related numbers. This makes your code easier to read and understand.

When you have a list of fixed options, like days of the week.
When you want to represent states, like traffic light colors.
When you want to group related constants together.
When you want to avoid using many separate #define or const values.
Syntax
C
enum EnumName {
    VALUE1,
    VALUE2,
    VALUE3
};

Each name inside the enum represents an integer starting from 0 by default.

You can assign specific numbers to names if you want.

Examples
This creates an enum named Day with three values starting from 0.
C
enum Day {
    SUNDAY,
    MONDAY,
    TUESDAY
};
Here, each color is assigned a specific number.
C
enum Color {
    RED = 1,
    GREEN = 2,
    BLUE = 4
};
You can use negative or zero values as well.
C
enum Status {
    SUCCESS = 0,
    ERROR = -1
};
Sample Program

This program uses an enum to represent traffic light colors. It prints a message based on the current light.

C
#include <stdio.h>

enum TrafficLight {
    RED,
    YELLOW,
    GREEN
};

int main() {
    enum TrafficLight light = RED;

    if (light == RED) {
        printf("Stop\n");
    } else if (light == YELLOW) {
        printf("Get ready\n");
    } else {
        printf("Go\n");
    }

    return 0;
}
OutputSuccess
Important Notes

Enum values are integers and can be used in comparisons and switches.

If you don't assign numbers, they start at 0 and increase by 1.

You can mix assigned and unassigned values; unassigned continue counting from the last assigned.

Summary

Enums give names to numbers to make code clearer.

Use enums when you have a fixed set of related options.

You can assign specific numbers or let them count automatically.