Enums

What Is an enum in C? Explained With an Example

An enum is a named list of integer constants. This guide shows how enums work in C with a short, complete example, and how C++ differs in syntax.

On this page
  1. The short answer
  2. An example in C
  3. Why not use #define?
  4. What changes in C++
  5. When to use an enum in C

The short answer

In C, an enum groups a set of named integer constants under one type name. You define the names once, then use them in place of raw numbers.

An example in C

#include <stdio.h>

enum Season { SPRING, SUMMER, AUTUMN, WINTER };

int main(void) {
    enum Season current = SUMMER;

    printf("Season value: %d\n", current);
    if (current == SUMMER) {
        printf("It is summer.\n");
    }
    return 0;
}

This program prints:

Season value: 1
It is summer.

SPRING is 0, SUMMER is 1, and the rest follow in order. The line enum Season current declares a variable of the enum type. The if compares that variable with a name, so the code reads in plain terms. The same program also compiles as C++.

Why not use #define?

C programmers often name numbers with #define:

#define SPRING 0
#define SUMMER 1
#define AUTUMN 2
#define WINTER 3

This works, but a macro is text substitution. The preprocessor replaces each name before the compiler runs, so the compiler only sees numbers. A macro also doesn’t belong to a type, so nothing groups SPRING with the other seasons.

An enum keeps the related names together under one type name. Many debuggers also show the name of an enum variable instead of only its number, which helps while you debug.

C doesn’t stop an enum variable from holding a number that has no name, so the enum is a convenience, not a safety check.

What changes in C++

The same idea carries over to C++, with a few differences:

  • You can leave out the enum keyword, so Season current = SUMMER; works.
  • Enumerator names of an unscoped enum have the enum’s own type, not int.
  • C++11 added enum class, which requires names like Season::SUMMER and doesn’t convert to int on its own.

When to use an enum in C

Use an enum when a value can only be one of a few fixed choices, such as a program mode, a menu option, or a state. Keep a plain int for values that are counts, sizes, or measurements, since those aren’t fixed names.

Enumerators are int values in C, which is the same integer type covered in primitive data types in c.

The complete guide to enums

Enums in C++ With Examples
Read the guide

Keep exploring

Guides from other topics

All topics →