Skip to content

Module 7 · Structures, Unions, Enums and typedef — topic 3 of 4

Enumerations

enum gives names to a set of related integer constants — days, menu choices, states. Learn default and explicit values, using enums with switch, and their limitations in C.

Beginner 11 min read·Lesson 29 of 37 in C Programming

Learning objectives

  • Declare enumerations with default and explicit values
  • Use enums to replace magic numbers in switch statements
  • Know that C enums are integers and are not range-checked

Definition

An enumeration is a distinct type whose values are named integer constants (enumerators). Enumerators have type int in C and take successive values starting at 0 unless explicitly assigned.

Introduction

Code like if (state == 2) hides meaning. if (state == STATE_RUNNING) explains itself. Enumerations let you declare such named constants as a group.

In C an enum is essentially a set of int constants with a type name for documentation. The compiler can warn when a switch over an enum misses a case, which catches real bugs.

Why it matters

Enums make menu-driven programs, state machines and error codes readable and less error-prone.

They are preferred over long lists of #define constants because they are grouped, scoped like other identifiers and visible in debuggers.

Detailed explanation

enum Weekday { MON, TUE, WED }; gives MON = 0, TUE = 1, WED = 2. Each enumerator without an explicit value is one more than the previous.

Explicit values: enum Status { OK = 0, NOT_FOUND = 404, SERVER_ERROR = 500 };. Values may repeat and need not be consecutive.

An enum variable can hold any int-compatible value; C does not check that it is one of the listed enumerators.

A common idiom adds a final enumerator such as COLOR_COUNT to know how many values there are, e.g. to size a lookup table of names.

With gcc -Wall, a switch over an enum without a default warns if an enumerator is not handled (-Wswitch).

Syntax

C
enum Color { RED, GREEN, BLUE, COLOR_COUNT };
enum Level { LOW = 1, MEDIUM = 5, HIGH = 10 };
enum Color c = GREEN;
if (c == GREEN) { /* ... */ }
  • Enumerator names share the ordinary identifier namespace, so prefixes (e.g. COLOR_RED) avoid clashes.
  • Print enum values with %d.
  • C23 allows specifying the underlying type: enum Small : unsigned char { A, B };.

Code examples

Default numbering

C
#include <stdio.h>
enum Weekday { MON, TUE, WED, THU, FRI, SAT, SUN };
int main(void) {
enum Weekday today = WED;
printf("WED = %d\n", today);
printf("weekend? %s\n", today >= SAT ? "yes" : "no");
return 0;
}
Output
WED = 2
weekend? no

Explicit values

C
#include <stdio.h>
enum HttpStatus { HTTP_OK = 200, HTTP_NOT_FOUND = 404, HTTP_ERROR = 500 };
int main(void) {
enum HttpStatus s = HTTP_NOT_FOUND;
printf("status %d\n", s);
return 0;
}
Output
status 404

More examples

A traffic-light state machine

C
#include <stdio.h>
typedef enum { RED, GREEN, YELLOW, LIGHT_COUNT } Light;
static const char *NAMES[LIGHT_COUNT] = {"RED", "GREEN", "YELLOW"};
static const int SECONDS[LIGHT_COUNT] = {30, 25, 5};
Light next(Light l) {
switch (l) {
case RED: return GREEN;
case GREEN: return YELLOW;
case YELLOW: return RED;
case LIGHT_COUNT: break;
}
return RED;
}
int main(void) {
Light l = RED;
int elapsed = 0;
for (int step = 0; step < 4; step++) {
printf("t=%3ds %-6s for %ds\n", elapsed, NAMES[l], SECONDS[l]);
elapsed += SECONDS[l];
l = next(l);
}
return 0;
}
Output
t=  0s RED    for 30s
t= 30s GREEN  for 25s
t= 55s YELLOW for 5s
t= 60s RED    for 30s

Step-by-step explanation

  • LIGHT_COUNT is 3, so it sizes both lookup tables automatically.
  • Enum values double as array indexes into NAMES and SECONDS.
  • next maps each state to its successor; listing every enumerator in the switch lets the compiler warn if a new state is added but not handled.
  • The loop simulates four transitions, accumulating elapsed time.

Expected output

Running “A traffic-light state machine” prints exactly:

TextOutput
t= 0s RED for 30s
t= 30s GREEN for 25s
t= 55s YELLOW for 5s
t= 60s RED for 30s

Practical applications

  • Protocol implementations name message types and states with enums.
  • Error codes in libraries are enums (e.g. errno-style values).
  • Game engines track entity states (IDLE, RUNNING, JUMPING) with enums.

Best practices

  • Use enums instead of magic numbers for related constants.
  • Prefix enumerators with the type name.
  • Add a _COUNT enumerator for table sizes and loops.

Common mistakes

Assuming enums are range-checked

Avoid

enum Color c = 42; /* compiles */

Prefer

enum Color c = BLUE;
if (c >= 0 && c < COLOR_COUNT) { /* valid */ }

C allows any integer in an enum variable. Validate values that come from input or files.

Enumerator name clashes

Avoid

enum Fruit { APPLE, ORANGE };
enum Color { RED, ORANGE };

Prefer

enum Fruit { FRUIT_APPLE, FRUIT_ORANGE };
enum Color { COLOR_RED, COLOR_ORANGE };

Enumerators share one namespace; two ORANGEs are a redefinition error. Prefix them.

Important notes

  • In C, enumerators have type int (C23 relaxes this when an underlying type is specified).
  • Unlike C++ enum class, C enums convert implicitly to and from integers.

Key takeaways

  • Enums name integer constants; numbering starts at 0 by default.
  • They are not range-checked in C.
  • Combine enums with switch and lookup tables for clear state logic.

Try it yourself

  1. 1
    Define enum Month and write a function returning the number of days in a month (ignore leap years).
  2. 2
    Write a menu loop using enum MenuChoice { ADD = 1, VIEW, DELETE, QUIT }.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

3 questions test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat is printed?
  • ModerateWhat is printed?
  • AdvancedWhich statement about C enumerations is correct?
Practise this topic