C Lesson 29 – Enums | Dataplexa

Enums in C

So far, you have used integers to represent values like options, states, or choices.

But using plain numbers often makes code confusing and error-prone.

This is where enums help.


What Is an Enum?

An enum (short for enumeration) is a user-defined data type that assigns names to integer values.

Enums make programs:

  • More readable
  • Easier to maintain
  • Less error-prone

Why Use Enums?

Compare these two approaches:

Without enum:


int status = 1;  // What does 1 mean?

With enum:


enum Status { ACTIVE, INACTIVE };
enum Status status = ACTIVE;

The second version clearly explains the meaning.


Defining an Enum


enum Day {
    MONDAY,
    TUESDAY,
    WEDNESDAY,
    THURSDAY,
    FRIDAY
};

By default:

  • MONDAY = 0
  • TUESDAY = 1
  • WEDNESDAY = 2
  • and so on…

Using an Enum Variable


enum Day today;
today = WEDNESDAY;

Internally, today stores an integer value.


Assigning Custom Values

You can assign your own values:


enum Level {
    LOW = 1,
    MEDIUM = 5,
    HIGH = 10
};

Each name maps to a specific integer.


Enum Example Program


#include <stdio.h>

enum Status {
    OFF,
    ON
};

int main() {
    enum Status device = ON;

    if (device == ON) {
        printf("Device is ON");
    } else {
        printf("Device is OFF");
    }

    return 0;
}

Enum vs #define

Enums are better than macros because:

  • They are type-safe
  • They improve readability
  • They are easier to debug

Enums are preferred in professional codebases.


Real-World Analogy

Think of enum like a labeled switch:

  • Instead of switch position 0 or 1
  • You label them OFF and ON

Same value — clearer meaning.


Where Enums Are Used

  • Menu-driven programs
  • State machines
  • Error codes
  • Operating systems

Mini Practice

  • Create an enum for traffic lights
  • RED, YELLOW, GREEN
  • Write a program to print the current light

Quick Quiz

Q1. What is the main purpose of enums?

To give meaningful names to integer values.

Q2. What is the default value of the first enum constant?

0

Q3. Can enums have custom values?

Yes.

Q4. Are enums stored as integers internally?

Yes.

Q5. Are enums better than plain numbers?

Yes, for readability and safety.