0
0
Cprogramming~5 mins

Enum usage in C

Choose your learning style9 modes available
Introduction

Enums help you give names to numbers. This makes your code easier to read and understand.

When you have a list of related options, like days of the week.
When you want to make code clearer by using names instead of numbers.
When you want to group related constants together.
When you want to avoid mistakes by using named values instead of random numbers.
Syntax
C
enum EnumName {
    VALUE1,
    VALUE2,
    VALUE3
};

Each name inside enum gets a number starting from 0 by default.

You can assign specific numbers to names if you want.

Examples
This creates an enum named Color with three values: RED=0, GREEN=1, BLUE=2.
C
enum Color {
    RED,
    GREEN,
    BLUE
};
Here, MONDAY starts at 1, so TUESDAY is 2, WEDNESDAY is 3.
C
enum Day {
    MONDAY = 1,
    TUESDAY,
    WEDNESDAY
};
You can assign any number, like 0 and -1 here.
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

Enums make your code easier to read and maintain.

By default, enum values start at 0 and increase by 1.

You can use enums to improve code safety by avoiding magic numbers.

Summary

Enums give names to numbers for better code clarity.

You can assign specific numbers or use default counting.

Use enums to group related constants and avoid errors.