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
enumkeyword, soSeason 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 likeSeason::SUMMERand doesn’t convert tointon 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.