Skip to content
StudyFame

Enumeration (enum) in C

What does if (day == 3) mean? Wednesday? Thursday? Nobody knows without a comment. With an enum, you write if (day == WEDNESDAY), and the code explains itself.

In this lesson you will create enumerations, see how C numbers their values, set your own values, use enums with switch, and compare enum with #define.

What You Will Learn

  • What an enum is and why it helps.
  • How to declare an enum and its variables.
  • Default values (0, 1, 2…) and custom values.
  • How to use enums with switch.
  • The difference between enum and #define.

What is enum in C?

Exam definition: An enumeration (enum) is a user-defined data type that consists of a set of named integer constants called enumerators. By default, the first enumerator is 0 and each next one is one more than the previous.

Memory trick: An enum is like the floor buttons in a lift: "Ground, First, Second…" are names, but inside the lift they are just numbers 0, 1, 2. You press names; the machine uses numbers.

Syntax of enum

enum weekday { MON, TUE, WED, THU, FRI, SAT, SUN };
/*              0    1    2    3    4    5    6   */

enum weekday today = WED;           /* today holds 2 */

enum level { LOW = 1, MEDIUM, HIGH = 10, CRITICAL };
/*           1        2       10         11        */

typedef enum { RED, YELLOW, GREEN } Signal;   /* with typedef */
Signal s = GREEN;
  • Enumerator names are usually written in CAPITALS, like other constants.
  • A value without = is previous + 1.
  • Two enumerators may have the same value, but two can't have the same name in one scope.
  • Enumerators are really int constants, so they print with %d.

Example 1: Default and Custom enum Values

#include <stdio.h>

enum weekday { MON, TUE, WED, THU, FRI, SAT, SUN };
enum level { LOW = 1, MEDIUM, HIGH = 10, CRITICAL };

int main(void)
{
    enum weekday today = FRI;
    enum weekday d;
    const char *names[] = {"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"};

    printf("MON = %d, WED = %d, SUN = %d\n", MON, WED, SUN);
    printf("LOW = %d, MEDIUM = %d, HIGH = %d, CRITICAL = %d\n",
           LOW, MEDIUM, HIGH, CRITICAL);

    printf("Today is %s (value %d)\n", names[today], today);
    printf("Weekend? %s\n", (today == SAT || today == SUN) ? "yes" : "no");

    printf("Working days:");
    for (d = MON; d <= FRI; d++)
        printf(" %s", names[d]);
    printf("\n");

    printf("sizeof(enum weekday) = %zu\n", sizeof(enum weekday));

    return 0;
}

Output

MON = 0, WED = 2, SUN = 6
LOW = 1, MEDIUM = 2, HIGH = 10, CRITICAL = 11
Today is Fri (value 4)
Weekend? no
Working days: Mon Tue Wed Thu Fri
sizeof(enum weekday) = 4

Code Explanation

  1. The weekday enumerators get 0 to 6 automatically.
  2. In level, MEDIUM follows LOW = 1 so it's 2; CRITICAL follows HIGH = 10 so it's 11.
  3. Because enumerators are integers, names[today] uses the enum as an array index: a handy way to print names.
  4. The loop for (d = MON; d <= FRI; d++) works since enum values are consecutive integers.
  5. An enum variable is usually the size of an int (4 bytes).

How enum Makes Code Safer and Clearer

  • Readable: state = PAID is clearer than state = 2.
  • Grouped: related constants live together in one type.
  • Debugger-friendly: debuggers can show WED instead of 2.
  • Switch-friendly: compilers can warn when a switch on an enum misses a case (-Wall).
  • Note: C does not stop you from storing any int in an enum variable (today = 42; compiles). Enums help clarity; they are not strict.

Example 2: Traffic Signal Using enum and switch

#include <stdio.h>

typedef enum { RED, YELLOW, GREEN } Signal;

Signal next_signal(Signal s)
{
    switch (s)
    {
        case RED:    return GREEN;
        case GREEN:  return YELLOW;
        case YELLOW: return RED;
    }
    return RED;
}

const char *action(Signal s)
{
    switch (s)
    {
        case RED:    return "Stop";
        case YELLOW: return "Get ready";
        case GREEN:  return "Go";
    }
    return "?";
}

int main(void)
{
    Signal s = RED;
    int i;

    for (i = 0; i < 4; i++)
    {
        printf("Signal %d: %s\n", s, action(s));
        s = next_signal(s);
    }

    return 0;
}

Output

Signal 0: Stop
Signal 2: Go
Signal 1: Get ready
Signal 0: Stop
  • case RED: is far clearer than case 0:.
  • typedef enum {...} Signal; lets us write Signal instead of enum signal.
  • Printing s with %d shows the underlying number (RED 0, GREEN 2, YELLOW 1).

enum vs #define

Pointenum#define
Handled byCompilerPreprocessor
ValuesAssigned automatically (0, 1, 2…)Each written by hand
GroupingRelated names form one typeSeparate, unrelated macros
ScopeFollows block scopeGlobal from the line onwards
Types allowedIntegers onlyAny value (float, string…)
DebuggingNames visible in the debuggerReplaced before compiling

Important Points to Remember

  • An enum is a set of named integer constants.
  • Default values start at 0 and go up by 1.
  • A value without = is previous + 1.
  • Enumerators print with %d; size is usually that of an int.
  • Great with switch and as array indexes.
  • Enum values must be integers; names must be unique in a scope.

Common Mistakes Beginners Make

MistakeWhat happensFix
Expecting the first value to be 1Off-by-one errorsDefault starts at 0 (or write = 1)
printf("%s", WED)Crash: WED is an intUse a names array or switch
Same enumerator in two enums: enum a {OK}; enum b {OK};Error: redeclarationUse different names (A_OK, B_OK)
enum rate {HALF = 0.5};Error: not an integerUse a const double or #define
Missing semicolon after }Compile errorWrite };

enum Practice Questions

  1. Define an enumeration.
  2. What are the values in enum c {A, B = 5, C, D = 2, E};?
  3. What is the default value of the first enumerator?
  4. Give three differences between enum and #define.
  5. Can enum values be floating-point numbers?
Show answers
  1. A user-defined type made of named integer constants (enumerators).
  2. A = 0, B = 5, C = 6, D = 2, E = 3.
  3. 0.
  4. enum is handled by the compiler, #define by the preprocessor; enum assigns values automatically; enum groups constants into one type and follows scope rules.
  5. No, only integers.

Coding Exercise

Create enum month {JAN = 1, FEB, ..., DEC}. Write a function that returns the number of days in a month (ignore leap years) using a switch on the enum, and print days for FEB, APR and DEC.

Show solution
#include <stdio.h>

enum month { JAN = 1, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC };

int days_in(enum month m)
{
    switch (m)
    {
        case FEB:
            return 28;
        case APR: case JUN: case SEP: case NOV:
            return 30;
        default:
            return 31;
    }
}

int main(void)
{
    printf("FEB (%d): %d days\n", FEB, days_in(FEB));
    printf("APR (%d): %d days\n", APR, days_in(APR));
    printf("DEC (%d): %d days\n", DEC, days_in(DEC));
    return 0;
}
FEB (2): 28 days
APR (4): 30 days
DEC (12): 31 days

Quick Quiz: enum in C (MCQ)

  1. In enum {X, Y, Z};, Z is:

    A) 1   B) 2   C) 3   D) 0

  2. In enum {P = 4, Q, R = 1, S};, S is:

    A) 5   B) 2   C) 6   D) 0

  3. Enumerators are constants of type:

    A) float   B) char *   C) int   D) double

  4. Which is handled by the compiler?

    A) #define   B) enum   C) #include   D) #ifdef

  5. Format specifier to print an enum value:

    A) %s   B) %d   C) %e   D) %c

Show answers
  1. B: 2.
  2. B: 2 (R = 1, so S = 2).
  3. C: int.
  4. B: enum.
  5. B: %d.

Quick Revision for Exams and Interviews

Read this before your exam. The highlighted words are the answer.

Must-remember facts

enumSet of named integer constants
Default start0, then +1
No = givenprevious + 1
Type of enumeratorsint (print with %d)
Best used withswitch, array indexes, states
vs #defineenum = compiler, grouped, auto values

Frequently asked questions

What is enum in C?
A user-defined type of named integer constants, starting at 0 by default.
What is the difference between enum and #define?
enum is handled by the compiler, gives automatic values and groups names; #define is text replacement, one value at a time.
Can two enum constants have the same value?
Yes, values can repeat, but names must be unique.

Remember

  • enum = lift buttons: names outside, numbers inside.
  • Starts at 0 unless you say otherwise.

Next Topic

Next lesson: Bit Fields in C. You will pack several small values into a few bits with bit fields.