An enum in C gives names to integer constants, and that is almost all it does. The compiler will happily store 42 in a variable whose enum only defines 0, 1 and 2, and it never checks. GCC, Clang and MSVC do not even agree on which integer type an enum is. Used well, enums still make C code far easier to read and give the compiler enough information to warn you when a switch misses a case.
This guide covers declaring enums and controlling their values, a real order-status example, switch statements that warn about missing cases, converting enums to strings, bit flags, the X-macro technique, the new C23 syntax for choosing an enum’s size, and the mistakes that cause real bugs. A short section at the end shows how C++ changes enums with enum class. Every program was compiled and tested with GCC, Clang and MSVC.
What Is an Enum in C?
An enum (enumeration) in C is a user-defined type made of a set of named integer constants, called enumerators. You write enum followed by an optional tag and a list of names in braces:
enum traffic_light { RED, AMBER, GREEN };
enum traffic_light light = GREEN;
Three facts explain most of how enums behave:
- The constants are plain
intvalues.REDis 0,AMBERis 1 andGREENis 2, and they can be used anywhere anintconstant can, includingcaselabels and array sizes. - An enum variable is an integer. Its exact integer type is chosen by the compiler, and C does not restrict it to the listed values.
- The names are global to their scope. Two enums in the same scope cannot both define
RED.
Use an enum whenever a variable holds one of a fixed set of choices: an order’s status, a log level, a day of the week, the state of a machine, or an error code.
Declaring an Enum and Setting Its Values
By default the first constant is 0 and each one after it is one more than the previous one. You can give any constant an explicit value, and the counting continues from there:
/* basics: declaring enums, the values the compiler assigns, explicit
values, aliases, and looping over a contiguous enum. */
#include <stdio.h>
/* Values start at 0 and go up by one. */
enum weekday { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY };
/* Explicit values, as in HTTP status codes. A constant without "=" is one
more than the constant before it. */
enum http_status {
HTTP_OK = 200,
HTTP_CREATED, /* 201 */
HTTP_NOT_FOUND = 404,
HTTP_SERVER_ERROR = 500,
};
/* Two names may share a value: here the last real level doubles as the
number of levels, so the enum can size an array. */
enum fan_speed { FAN_OFF, FAN_LOW, FAN_MEDIUM, FAN_HIGH, FAN_SPEED_COUNT, FAN_MAX = FAN_HIGH };
int main(void)
{
enum weekday today = WEDNESDAY;
printf("WEDNESDAY = %d, SUNDAY = %d\n", (int)today, SUNDAY);
printf("weekend? %s\n", today >= SATURDAY ? "yes" : "no");
printf("HTTP_OK = %d, HTTP_CREATED = %d, HTTP_NOT_FOUND = %d\n", HTTP_OK, HTTP_CREATED, HTTP_NOT_FOUND);
static const char *const fan_names[FAN_SPEED_COUNT] = {"off", "low", "medium", "high"};
for (enum fan_speed s = FAN_OFF; s < FAN_SPEED_COUNT; s++)
printf("fan %d: %s%s\n", (int)s, fan_names[s], s == FAN_MAX ? " (max)" : "");
printf("sizeof(enum weekday) = %zu, sizeof(int) = %zu\n", sizeof(enum weekday), sizeof(int));
return 0;
}
Output:
WEDNESDAY = 2, SUNDAY = 6
weekend? no
HTTP_OK = 200, HTTP_CREATED = 201, HTTP_NOT_FOUND = 404
fan 0: off
fan 1: low
fan 2: medium
fan 3: high (max)
sizeof(enum weekday) = 4, sizeof(int) = 4
What this shows:
- Default values start at 0.
WEDNESDAYis 2 andSUNDAYis 6, so comparisons such astoday >= SATURDAYwork on the order of declaration. - Explicit values may be anything that fits.
HTTP_CREATEDhas no value of its own, so it isHTTP_OK + 1, which is 201. - Two names may share a value.
FAN_MAXis an alias forFAN_HIGH. - A final
COUNTconstant is the number of values before it, as long as they start at 0 with no gaps. It sizes thefan_namestable and ends the loop. Keep it last, or it stops being the count.
An enum’s size is usually 4 bytes, the same as int, but the standard does not promise this, as the section on what type an enum is shows.
A Real-World Example: Order Status
An online shop tracks every order through a series of stages. That is a natural enum, and it shows the decisions that matter in real code: which numbers to use, how to name each value, how to read one from text, and which changes are allowed.
#ifndef ORDER_H
#define ORDER_H
#include <stdbool.h>
/* The stages of an online order. The numbers are written to the database,
so each one is fixed explicitly and never reused: adding a stage means
adding a new number at the end, not renumbering. Zero is left out on
purpose, so a status that was never set (a zeroed struct) is invalid. */
typedef enum order_status {
ORDER_PENDING = 1,
ORDER_PAID = 2,
ORDER_SHIPPED = 3,
ORDER_DELIVERED = 4,
ORDER_CANCELLED = 5,
} order_status;
/* True if v is one of the values above. Check this before converting a
number from a file, the network or the user into an order_status. */
bool order_status_valid(int v);
/* "pending", "paid", ...; "invalid" for any other value. */
const char *order_status_name(order_status s);
/* Parses a name such as "shipped". Returns false for anything else. */
bool order_status_parse(const char *text, order_status *out);
/* The business rules: which stage may follow which. */
bool order_can_move(order_status from, order_status to);
#endif
#include "order.h"
#include <string.h>
bool order_status_valid(int v)
{
return v >= ORDER_PENDING && v <= ORDER_CANCELLED;
}
/* A switch with no default: if a new status is added and not handled
here, GCC and Clang warn (-Wswitch, part of -Wall). */
const char *order_status_name(order_status s)
{
switch (s) {
case ORDER_PENDING: return "pending";
case ORDER_PAID: return "paid";
case ORDER_SHIPPED: return "shipped";
case ORDER_DELIVERED: return "delivered";
case ORDER_CANCELLED: return "cancelled";
}
return "invalid";
}
bool order_status_parse(const char *text, order_status *out)
{
for (int v = ORDER_PENDING; v <= ORDER_CANCELLED; v++) {
if (strcmp(text, order_status_name((order_status)v)) == 0) {
*out = (order_status)v;
return true;
}
}
return false;
}
bool order_can_move(order_status from, order_status to)
{
switch (from) {
case ORDER_PENDING: return to == ORDER_PAID || to == ORDER_CANCELLED;
case ORDER_PAID: return to == ORDER_SHIPPED || to == ORDER_CANCELLED;
case ORDER_SHIPPED: return to == ORDER_DELIVERED;
case ORDER_DELIVERED: return false;
case ORDER_CANCELLED: return false;
}
return false;
}
Three decisions in this code avoid bugs that are easy to write:
- The values are explicit and start at 1. The numbers end up in a database. Writing them out makes clear that they must never change, and leaving out 0 means a status that was never set (in a zeroed
struct, say) is detected as invalid instead of passing for “pending”. order_status_name()uses aswitchwith nodefault. If someone addsORDER_REFUNDEDand forgets this function, GCC and Clang warn. Thereturn "invalid";after theswitchhandles values outside the enum.- Text is converted to an enum in one place.
order_status_parse()accepts only the exact names, andorder_can_move()encodes the business rules: a shipped order can be delivered but no longer cancelled.
order_demo applies a file of status updates to a few orders, the way an order service processes events:
# order status
1001 paid
1002 paid
1001 shipped
1002 cancelled
1003 paid
1001 cancelled
1003 refunded
1001 delivered
1004 shipped
Output:
order 1001: pending -> paid
order 1002: pending -> paid
order 1001: paid -> shipped
order 1002: paid -> cancelled
order 1003: pending -> paid
order 1001: shipped -> cancelled not allowed
order 1003: "refunded" is not a status, ignored
order 1001: shipped -> delivered
order 1004: pending -> shipped not allowed
Final status (stored as numbers):
order 1001 delivered = 4
order 1002 cancelled = 5
order 1003 paid = 2
order 1004 pending = 1
3 updates rejected
The rejected lines are the interesting ones. Order 1001 cannot be cancelled after it has shipped, “refunded” is not a status at all, and order 1004 cannot ship before it has been paid. The final table shows the numbers that would be stored, which is why those numbers are fixed in the header.
Using an Enum in a switch Statement
A switch over an enum reads better than a chain of if-else statements, and it gives the compiler a chance to help. When a switch on an enum value has no default and does not handle every constant, GCC and Clang warn. The warning is -Wswitch, and it is part of -Wall.
pitfalls/missing_case.c shows what happens when a new constant is added to an enum and one switch is not updated:
enum status { PENDING, PAID, SHIPPED, DELIVERED, REFUNDED };
static int delivery_days(enum status s)
{
switch (s) {
case PENDING: return 5;
case PAID: return 4;
case SHIPPED: return 2;
case DELIVERED: return 0;
}
return -1; /* reached only for REFUNDED */
}
GCC reports it at compile time:
warning: enumeration value 'REFUNDED' not handled in switch [-Wswitch]
If the warning is ignored, the program runs and quietly returns the fallback value:
Output:
status 0: 5 days
status 1: 4 days
status 2: 2 days
status 3: 0 days
status 4: -1 days
Two habits make this warning work for you:
- Leave out
defaultwhen aswitchis meant to cover every enum value. Adefaultbranch tells the compiler you have handled everything else, so it stops warning about new constants. Put the fallback after theswitchinstead, asorder_status_name()does. - Build with warnings as errors (
-Werror, or-Werror=switchfor just this one). The test suite for this article buildsmissing_case.cthat way and checks that the build fails with a message namingREFUNDED.
MSVC does not warn by default. Its equivalent, warning C4062, is off even at /W4. Turn it on with /w44062, or make it an error with /we4062 as the test suite does.
Converting an Enum to a String
C has no built-in way to print an enum’s name: printf("%d") prints the number. There are three common ways to get the name.
1. A switch. This is what order_status_name() does. It is the safest, because -Wswitch catches a missing name, and it works for any values, including gaps and large numbers.
2. A lookup table with designated initializers. Each name is placed at the index of its constant, so the order of the lines no longer matters:
static const char *const names[] = {
[ORDER_PENDING] = "pending",
[ORDER_PAID] = "paid",
[ORDER_SHIPPED] = "shipped",
[ORDER_DELIVERED] = "delivered",
[ORDER_CANCELLED] = "cancelled",
};
This is fast and compact. But indexing it with a value that is not a valid status reads outside the array, which is mistake number 1 below.
3. An X-macro. One list generates both the enum and its names, so they cannot drift apart. This program uses it for log levels:
/* log_levels: an X-macro keeps an enum and its names in one list, so they
cannot drift apart when a level is added.
usage: log_levels [debug|info|warning|error] (the minimum level to show) */
#include <stdio.h>
#include <string.h>
#define LOG_LEVELS(X) \
X(DEBUG, "debug") \
X(INFO, "info") \
X(WARNING, "warning") \
X(ERROR, "error")
enum log_level {
#define AS_ENUM(name, text) LOG_##name,
LOG_LEVELS(AS_ENUM)
#undef AS_ENUM
LOG_LEVEL_COUNT
};
static const char *const log_level_names[] = {
#define AS_NAME(name, text) text,
LOG_LEVELS(AS_NAME)
#undef AS_NAME
};
_Static_assert(sizeof log_level_names / sizeof log_level_names[0] == LOG_LEVEL_COUNT,
"every log level needs a name");
static void log_message(enum log_level minimum, enum log_level level, const char *text)
{
if (level >= minimum)
printf("[%-7s] %s\n", log_level_names[level], text);
}
int main(int argc, char **argv)
{
enum log_level minimum = LOG_INFO;
if (argc > 1) {
int found = 0;
for (int i = 0; i < LOG_LEVEL_COUNT; i++)
if (strcmp(argv[1], log_level_names[i]) == 0) {
minimum = (enum log_level)i;
found = 1;
}
if (!found) {
fprintf(stderr, "log_levels: unknown level \"%s\"\n", argv[1]);
return 2;
}
}
printf("%d levels; showing %s and above\n", LOG_LEVEL_COUNT, log_level_names[minimum]);
log_message(minimum, LOG_DEBUG, "cache lookup for key 42");
log_message(minimum, LOG_INFO, "server started on port 8080");
log_message(minimum, LOG_WARNING, "disk 91% full");
log_message(minimum, LOG_ERROR, "payment service unreachable");
return 0;
}
Output:
4 levels; showing info and above
[info ] server started on port 8080
[warning] disk 91% full
[error ] payment service unreachable
With a higher minimum level, the debug and info messages are filtered out:
Output:
4 levels; showing warning and above
[warning] disk 91% full
[error ] payment service unreachable
LOG_LEVELS(X) expands the macro X once per level. Defined as AS_ENUM, it produces LOG_DEBUG, LOG_INFO, .... Defined as AS_NAME, it produces "debug", "info", .... Adding a level is one new line in the list, and the _Static_assert stops the build if the table and the enum ever disagree. X-macros look unusual at first, but they are common in large C code bases for error codes, opcodes and configuration keys.
Enum Flags: Combining Values with Bitwise Operators
When a variable needs to hold several options at once (permissions, features, file modes), give each enum constant its own bit. Then any combination fits in one integer, and the bitwise operators |, & and ~ add, test and remove them:
/* flags: an enum of single bits, combined into a set of permissions,
as in a file-sharing app. Each constant is one bit, so any combination
fits in one unsigned int. */
#include <stdio.h>
enum permission {
PERM_READ = 1u << 0,
PERM_WRITE = 1u << 1,
PERM_SHARE = 1u << 2,
PERM_DELETE = 1u << 3,
};
/* A combination such as READ | WRITE is not one of the enum's constants,
so the set is kept in an unsigned int rather than an enum permission. */
typedef unsigned int permissions;
static void show(const char *who, permissions p)
{
printf("%-8s 0x%X:", who, p);
if (p == 0)
printf(" none");
if (p & PERM_READ)
printf(" read");
if (p & PERM_WRITE)
printf(" write");
if (p & PERM_SHARE)
printf(" share");
if (p & PERM_DELETE)
printf(" delete");
putchar('\n');
}
int main(void)
{
permissions viewer = PERM_READ;
permissions editor = PERM_READ | PERM_WRITE;
permissions owner = PERM_READ | PERM_WRITE | PERM_SHARE | PERM_DELETE;
show("viewer", viewer);
show("editor", editor);
show("owner", owner);
editor |= PERM_SHARE; /* grant */
show("editor+", editor);
owner &= ~(permissions)PERM_DELETE; /* revoke */
show("owner-", owner);
/* Test for all of several bits at once: compare with the mask. */
permissions needed = PERM_READ | PERM_SHARE;
printf("viewer can read and share? %s\n", (viewer & needed) == needed ? "yes" : "no");
printf("editor can read and share? %s\n", (editor & needed) == needed ? "yes" : "no");
return 0;
}
Output:
viewer 0x1: read
editor 0x3: read write
owner 0xF: read write share delete
editor+ 0x7: read write share
owner- 0x7: read write share
viewer can read and share? no
editor can read and share? yes
Things to notice:
- Each constant is a power of two, written as
1u << nso the bit position is visible.PERM_DELETEis bit 3, value 8. - The set is stored in an
unsigned int, not anenum permission.PERM_READ | PERM_WRITEis 3, which is not one of the enum’s constants. C would allow storing it in the enum variable, but the type would then promise something it does not mean. - To check for several flags at once, compare against the whole mask.
(p & needed) == neededis true only when every bit inneededis set;p & neededalone is true when any one of them is.
What Type Is an Enum in C?
Enumeration constants have type int. The enum type itself is “compatible with” an integer type that the compiler chooses (C17 §6.7.2.2), as long as it can hold all the values. Compilers choose differently. underlying.c asks in two ways: with _Generic, which selects a string based on the type of its argument, and by storing −1 and reading it back, which shows whether the type is signed:
/* underlying: which integer type the compiler picked for each enum.
The C standard leaves this to the implementation (C17 6.7.2.2), so
the output differs between compilers. Enumeration constants
themselves are always int before C23. */
#include <stdio.h>
enum color { RED, GREEN, BLUE }; /* no negative values */
enum temperature { COLD = -10, HOT = 40 }; /* a negative value */
#define TYPE_NAME(x) _Generic((x), \
int: "int", unsigned int: "unsigned int", \
long: "long", unsigned long: "unsigned long", \
long long: "long long", unsigned long long: "unsigned long long", \
char: "char", signed char: "signed char", unsigned char: "unsigned char", \
short: "short", unsigned short: "unsigned short", \
default: "another type")
int main(void)
{
enum color c = GREEN;
enum temperature t = HOT;
(void)t; /* _Generic only looks at the type; it never evaluates t */
printf("the constant GREEN has type %s\n", TYPE_NAME(GREEN));
printf("enum color is compatible with %s\n", TYPE_NAME(c));
printf("enum temperature is compatible with %s\n", TYPE_NAME(t));
printf("sizeof(enum color) = %zu\n", sizeof c);
/* A second test that works the same way on every compiler: store -1
and read it back. A signed type keeps -1; an unsigned one wraps. */
enum color probe = (enum color)-1;
long long back = probe;
printf("(enum color)-1 reads back as %lld: %s\n", back, back < 0 ? "signed" : "unsigned");
return 0;
}
| Question | GCC 13.3 | Clang 18 | MSVC |
|---|---|---|---|
Type of the constant GREEN | int | int | int |
_Generic says enum color is compatible with | unsigned int | unsigned int | no integer type (default) |
_Generic says enum temperature is compatible with | int | int | no integer type (default) |
sizeof(enum color) | 4 | 4 | 4 |
(enum color)-1 reads back as | 4294967295 (unsigned) | 4294967295 (unsigned) | -1 (signed) |
Three things stand out:
- GCC and Clang chose an unsigned type for
enum color, whose values are all non-negative, andintonce a negative value appears. Storing −1 inenum colorreads back as 4294967295. - MSVC chose a signed type. The same −1 reads back as −1, and the size is 4 bytes. So the same
enum coloris unsigned on one compiler and signed on another, and both are correct C. - MSVC’s
_Genericmatched the enum to no integer type at all and fell through todefault. The standard requires every enum to be compatible with some integer type, and_Genericselects by compatibility, so this is a quirk of MSVC’s_Generic, not a third answer. It is also why the program has the second, portable test: when a compile-time check gives a surprising answer, confirm it with a runtime one.
In everyday code this rarely matters, but it does in three places:
- Printing. Cast to
intbefore passing an enum toprintf("%d"). That is always correct, whichever type the compiler chose. - Comparisons with negative numbers. If the enum is unsigned,
if (color < 0)is never true, and code that uses −1 as a “none” value must define it inside the enum. - Binary layouts. Writing a struct containing an enum to a file or a network packet bakes in the compiler’s choice. GCC’s
-fshort-enumsoption even shrinks enums to the smallest type that fits, which changes structure layouts and breaks compatibility with code built without it. Store enums in files as fixed-width integers such asuint8_torint32_t, or use the C23 syntax below.
typedef enum and Naming Conventions
Writing enum order_status everywhere is verbose, so most C code adds a typedef, as order.h does:
typedef enum order_status { ORDER_PENDING = 1, /* ... */ } order_status;
Now order_status alone is the type. Keeping the tag (enum order_status) as well is useful because a tag can be forward-declared and appears in debugger output.
Enumerator names share one namespace with variables, functions and typedefs in the same scope. Two enums cannot both define NONE:
/* Must NOT compile: enumeration constants share one namespace with
variables and functions, so two enums in the same scope cannot both
have a constant called NONE. */
enum alignment { NONE, LEFT, RIGHT };
enum border { NONE, THIN, THICK };
int main(void)
{
return LEFT;
}
GCC: error: redeclaration of enumerator 'NONE'
Clang: error: redefinition of enumerator 'NONE'
That is why C enums conventionally prefix every constant with the type’s name, as in ORDER_, LOG_ and PERM_. Uppercase names follow the convention for constants. Short names such as OK, ERROR or NONE also collide with macros in system headers; Windows headers, for example, define ERROR.
enum vs #define vs const int
All three can name a constant, but they are not interchangeable:
| Property | enum constant | #define | const int |
|---|---|---|---|
| Has a type the compiler checks | int (the enum type for variables) | No, it is text | Yes, int |
Usable in case labels and array sizes | Yes | Yes | No (C17); yes with C23 constexpr |
| Groups related values into one type | Yes | No | No |
-Wswitch warns about missing values | Yes | No | No |
| Visible by name in a debugger | Yes | Usually not | Yes |
| Respects block scope | Yes | No, active until #undef | Yes |
| Any type (floating point, strings, 64-bit before C23) | No, int only | Yes | Yes |
The case label row surprises many programmers. In C, unlike C++, a const int is not a constant expression:
/* Must NOT compile with warnings as errors: a const int is not an
integer constant expression in C, so it cannot be a case label.
(An enumeration constant can; see src/order.c.) */
static const int MAX_RETRIES = 3;
int give_up(int attempts)
{
switch (attempts) {
case MAX_RETRIES:
return 1;
default:
return 0;
}
}
int main(void)
{
return give_up(1);
}
GCC: error: case label does not reduce to an integer constant
Clang: warning: expression is not an integer constant expression; folding it to a constant is a GNU extension
GCC rejects the program. Clang accepts it as an extension and only warns, so code that builds with Clang can fail on another compiler. An enum constant has neither problem.
Use an enum for a set of related integer choices, #define for values the preprocessor needs (#if, conditional compilation), and const variables for typed values that do not need to be constant expressions.
C23: Choosing an Enum’s Underlying Type
C23 lets you write the integer type after a colon, as C++ has allowed since C++11. The feature comes from WG14 paper N3030:
/* c23_enum: C23 lets an enum name its underlying type. Built only by
compilers that support it (GCC 13+, Clang 18+ with -std=c2x or -std=c23). */
#include <stdio.h>
enum status_byte : unsigned char { S_PENDING = 1, S_PAID, S_SHIPPED, S_DELIVERED, S_CANCELLED };
enum status_plain { P_PENDING = 1, P_PAID, P_SHIPPED, P_DELIVERED, P_CANCELLED };
/* Constants may now be wider than int when the type says so. */
enum file_size : long long { MAX_UPLOAD = 5LL * 1024 * 1024 * 1024 }; /* 5 GiB */
struct shipment_small { enum status_byte status; unsigned char warehouse; unsigned short weight_kg; };
struct shipment_plain { enum status_plain status; unsigned char warehouse; unsigned short weight_kg; };
int main(void)
{
printf("sizeof(enum status_byte) = %zu\n", sizeof(enum status_byte));
printf("sizeof(enum status_plain) = %zu\n", sizeof(enum status_plain));
printf("struct with byte enum: %zu bytes\n", sizeof(struct shipment_small));
printf("struct with plain enum: %zu bytes\n", sizeof(struct shipment_plain));
printf("1,000,000 shipments: %zu vs %zu bytes\n",
1000000 * sizeof(struct shipment_small), 1000000 * sizeof(struct shipment_plain));
printf("MAX_UPLOAD = %lld\n", (long long)MAX_UPLOAD);
return 0;
}
Output:
sizeof(enum status_byte) = 1
sizeof(enum status_plain) = 4
struct with byte enum: 4 bytes
struct with plain enum: 8 bytes
1,000,000 shipments: 4000000 vs 8000000 bytes
MAX_UPLOAD = 5368709120
A one-byte status halves the size of this shipment record, which matters when there are millions of them or when the layout must match a file format byte for byte. A fixed type also allows constants outside the int range, such as the 5 GiB MAX_UPLOAD. The C23 rules also allow enums without a fixed type to hold values beyond int, with the compiler choosing a wider type.
This needs a compiler with C23 support: GCC 13 or newer and Clang 18 or newer, with -std=c2x or -std=c23. The program was built with both. MSVC’s C compiler does not support it yet, so the repository builds this one program only where the compiler accepts it.
Common Mistakes with Enums in C
1. Trusting a number to be a valid enum value
Values that come from outside the program, such as a file, a database, a network packet or user input, are plain integers. C lets you convert any of them to an enum without complaint. pitfalls/out_of_range.c reads three statuses, one of which (7) was written by a different program and is not a valid status:
/* Pitfall: trusting a number to be a valid enum value.
C lets any int be stored in an enum variable. Statuses read back from a
file arrive as plain numbers, and one of them (7) is not an order status,
because another program wrote it. Using it to index a table of names
reads past the end of the table.
usage: pitfall_out_of_range checked (validates first: safe)
pitfall_out_of_range unchecked (indexes directly: undefined behavior) */
#include "order.h"
#include <stdio.h>
#include <string.h>
static const char *const names[] = {
[ORDER_PENDING] = "pending",
[ORDER_PAID] = "paid",
[ORDER_SHIPPED] = "shipped",
[ORDER_DELIVERED] = "delivered",
[ORDER_CANCELLED] = "cancelled",
};
int main(int argc, char **argv)
{
int checked = argc > 1 && strcmp(argv[1], "checked") == 0;
const int from_file[] = {2, 4, 7};
for (size_t i = 0; i < sizeof from_file / sizeof from_file[0]; i++) {
int v = from_file[i];
if (checked && !order_status_valid(v)) {
printf("record %zu: status %d is not valid, skipped\n", i, v);
continue;
}
order_status s = (order_status)v; /* C accepts any value */
printf("record %zu: status %d = %s\n", i, v, names[s]);
}
return 0;
}
With validation, the bad record is skipped:
Output:
record 0: status 2 = paid
record 1: status 4 = delivered
record 2: status 7 is not valid, skipped
Without it, names[7] reads past the end of a five-element table. That is undefined behavior: the program might print garbage, crash, or seem to work. UndefinedBehaviorSanitizer stops it at the bad index:
out_of_range.c:35: runtime error: index 7 out of bounds for type 'char *[6]'
With AddressSanitizer alone, the same line is reported as a global-buffer-overflow. The fix is the one order.h provides: check every number from outside with order_status_valid() before converting it. In code that handles untrusted input, this check is a security requirement, not a style choice.
2. Adding a constant in the middle of a stored enum
Enum values are numbers, and numbers saved to a file or database outlive the code that wrote them. Inserting a new constant in the middle of an enum without explicit values renumbers everything after it:
/* Pitfall: inserting a new constant in the middle of an enum whose values
are stored outside the program.
Version 1 of a shop saved order statuses to its database as numbers.
Version 2 added ON_HOLD after PAID, without explicit values, so every
later constant moved up by one. The old records now read back wrong. */
#include <stdio.h>
#include <string.h>
enum status_v1 { V1_PENDING, V1_PAID, V1_SHIPPED, V1_DELIVERED };
static const char *const names_v1[] = {"pending", "paid", "shipped", "delivered"};
enum status_v2 { V2_PENDING, V2_PAID, V2_ON_HOLD, V2_SHIPPED, V2_DELIVERED };
static const char *const names_v2[] = {"pending", "paid", "on hold", "shipped", "delivered"};
int main(void)
{
const int saved_by_v1[] = {V1_PAID, V1_SHIPPED, V1_DELIVERED};
printf("%-6s %-10s %-10s\n", "value", "saved as", "read as");
for (int i = 0; i < 3; i++) {
int v = saved_by_v1[i];
printf("%-6d %-10s %-10s%s\n", v, names_v1[v], names_v2[v],
strcmp(names_v1[v], names_v2[v]) != 0 ? " <- wrong" : "");
}
return 0;
}
Output:
value saved as read as
1 paid paid
2 shipped on hold <- wrong
3 delivered shipped <- wrong
Records saved as “shipped” now read back as “on hold”, and delivered orders appear merely shipped. Nothing fails; the data is just wrong. When values are stored or sent anywhere, give every constant an explicit value, and add new constants at the end with new numbers.
3. Adding a default branch to an enum switch
A default branch silences -Wswitch, so the compiler can no longer tell you about constants added later. Use default only when you really mean “everything else”, and otherwise handle invalid values after the switch, as shown earlier.
4. Forgetting that enum names are global
Unprefixed names such as NONE, ERROR or RED collide with other enums, with variables, and with macros from headers. Prefix every constant with its type’s name.
5. Assuming an enum’s size or signedness
Writing sizeof(enum ...) bytes to a file, or comparing an enum with −1, depends on a choice the standard leaves to the compiler. GCC and Clang chose an unsigned type where MSVC chose a signed one. Use fixed-width integers for storage, or C23’s enum name : type syntax.
Enums in C++: enum class
C++ keeps C’s enums, with one convenience: the enum keyword is optional when declaring a variable, so Weekday day; works without enum or a typedef. C++11 then added enum class, a scoped enumeration that fixes the weaknesses covered above:
- Scoped names. The constants are written
Signal::red, so two enum classes can both havered. - No implicit conversions. An
enum classvalue does not turn into anintunless you writestatic_cast<int>. - A chosen underlying type.
enum class Signal : std::uint8_tis one byte. C23 borrowed this syntax.
// enum_class: how C++ changes enums. A plain enum works as in C (and the
// enum keyword is optional when declaring a variable); an enum class adds
// scoped names, no implicit conversion to int, and a chosen underlying type.
#include <cstdint>
#include <iostream>
#include <string_view>
#include <type_traits>
enum Weekday { monday, tuesday, wednesday }; // plain, as in C
enum class Signal : std::uint8_t { red, amber, green }; // scoped, one byte
enum class Light : std::uint8_t { off, red, green }; // "red" again: no clash
constexpr std::string_view name(Signal s)
{
switch (s) {
case Signal::red: return "red";
case Signal::amber: return "amber";
case Signal::green: return "green";
}
return "invalid";
}
constexpr Signal next(Signal s)
{
switch (s) {
case Signal::red: return Signal::green;
case Signal::green: return Signal::amber;
case Signal::amber: return Signal::red;
}
return Signal::red;
}
int main()
{
Weekday day = tuesday; // no "enum" keyword needed in C++
std::cout << "tuesday = " << day << '\n';
Signal s = Signal::red;
for (int i = 0; i < 4; ++i) {
std::cout << name(s) << " (" << static_cast<int>(s) << ")\n";
s = next(s);
}
static_assert(sizeof(Signal) == 1, "the underlying type is std::uint8_t");
static_assert(std::is_same_v<std::underlying_type_t<Signal>, std::uint8_t>);
std::cout << "sizeof(Signal) = " << sizeof(Signal) << ", sizeof(Weekday) = " << sizeof(Weekday) << '\n';
std::cout << "Signal::red = " << static_cast<int>(Signal::red) << ", Light::red = "
<< static_cast<int>(Light::red) << ": same name, two scopes, no clash\n";
}
Output:
tuesday = 1
red (0)
green (2)
amber (1)
red (0)
sizeof(Signal) = 1, sizeof(Weekday) = 4
Signal::red = 0, Light::red = 1: same name, two scopes, no clash
C++ is also stricter than C about conversions. The first line below compiles in C (with a plain enum), and both are errors in C++:
Color c = 1; // int to enum: error in C++, even for a plain enum
int n = Signal::green; // enum class to int: error; use static_cast<int>
g++: error: invalid conversion from 'int' to 'Color' [-fpermissive]
g++: error: cannot convert 'Signal' to 'int' in initialization
clang++: error: cannot initialize a variable of type 'Color' with an rvalue of type 'int'
The repository’s tests check that both programs fail to compile with GCC, Clang and MSVC.
How the Code Is Tested
An enum example is easy to write and easy to get subtly wrong, so the tests check more than the output.
- Byte-for-byte output. Every program must print exactly the output shown in this article, except
underlying, whose answer is up to the compiler. - Programs that must not compile. Five programs, including the name clash, the
const intcase label, the two C++ conversions andmissing_case.cbuilt with its warning as an error, must fail to build with a message that names the problem. A build that fails for some unrelated reason does not count as a pass. - Unit tests for the order library. These check that exactly the values 1 to 5 are valid, that every name parses back to its value, that near-misses such as “Paid” and “paid ” are rejected, and that all 25 status changes follow the rules.
- Deliberate mistakes.
tests/mutations.pyputs eight mistakes into the order library and confirms the unit tests catch each one:
| Deliberate mistake | Unit-test check that failed |
|---|---|
| valid range starts at 0 | order_status_valid(v) == (v >= 1 && v <= 5) |
| valid range misses the last status | order_status_valid(v) == (v >= 1 && v <= 5) |
| two statuses share a name | order_status_parse(name, &back) && back == (order_status)v |
| parse skips the last status | order_status_parse(name, &back) && back == (order_status)v |
| parse accepts a prefix | !order_status_parse("", &s) |
| shipped orders can be cancelled | order_can_move((order_status)from, (order_status)to) == (allowed[from][to] == 1) |
| an order can skip payment | order_can_move((order_status)from, (order_status)to) == (allowed[from][to] == 1) |
| invalid status moves anywhere | !order_can_move((order_status)0, ORDER_PAID) |
Key Takeaways
- An enum is a set of named
intconstants. Values start at 0 and go up by one unless you give them explicitly. - C does not check enum values. Validate every number that comes from a file, the network or the user before treating it as an enum, especially before using it as an array index.
- Leave out
defaultin aswitchthat should cover every value, so-Wswitchwarns when a constant is added. MSVC needs/w44062to give the same warning. - Give stored enums explicit values, and only ever append. Inserting a constant in the middle silently renumbers saved data.
- Use one bit per constant for flags, and keep combinations in an unsigned integer.
- An enum’s integer type is up to the compiler: GCC and Clang made
enum colorunsigned, and MSVC made it signed. C23’senum name : typefixes it. - Prefix enum constants with the type’s name, because they share one namespace with everything else in scope.
Conclusion
Enums are one of the cheapest ways to make C code clearer: a switch over ORDER_SHIPPED and ORDER_DELIVERED explains itself, where one over 3 and 4 does not. The catch is that a C enum is only a naming system on top of integers. The compiler will not stop you from storing an invalid value, reordering stored numbers, or relying on a size it never promised. Explicit values, validation at the boundaries, switch statements without default and warnings turned into errors cover nearly all of it.
For more of the language, see the C programming section.
Source Code and Tests
All programs on this page are in the types/enums directory of the MYCPLUS C examples repository.
Build, test and run:
cmake -S . -B build
cmake --build build
ctest --test-dir build --output-on-failure
./build/order_demo data/events.txt
What the build checks.
- Compilers: GCC and Clang under C11 and C17, plus C++17, with
-Wall -Wextra -pedantic -Werror, and MSVC under/W4 /WX.missing_case.cis the one program allowed to build with a warning, because the warning is the lesson. - Output: every program prints exactly what is shown here.
- Compile failures: the five programs that must not compile fail with the expected message.
- Sanitizers and mutations: the tests run clean under AddressSanitizer and UndefinedBehaviorSanitizer, the unchecked lookup is caught, and all eight deliberate mistakes are caught.
What I Verified
Everything in the Ubuntu column was run for this article on Ubuntu 24.04 (x86-64, GCC 13.3, Clang 18, CMake 3.28, MinGW-w64 GCC 13). The WSL and Windows columns come from the run_all.sh and run_all.ps1 scripts in the repository.
| Check | Ubuntu 24.04 | WSL (Ubuntu) | Windows 11 |
|---|---|---|---|
Builds with warnings as errors: GCC and Clang (C11, C17, C++17) on Linux, MSVC /W4 /WX on Windows | GCC and Clang, C11 and C17: passed | GCC 13.3 and Clang 18, C11 and C17: passed | MSVC /W4 /WX, C11 and C17: built |
| CTest: unit tests, byte-for-byte outputs, and 5 programs that must fail to compile | 17 of 17 in all four configurations | 17 of 17 in all four configurations | 16 of 16 in C11 and in C17 (no C23 program) |
C23 enum name : type program | Built and checked with GCC 13 and Clang 18 | Built and checked with GCC and Clang | Not built (MSVC’s C compiler does not support it) |
| AddressSanitizer and UndefinedBehaviorSanitizer, every test | 17 of 17, clean | 17 of 17, clean | Not applicable |
The unchecked lookup in out_of_range.c is caught | UBSan: index 7 out of bounds | UBSan: index 7 out of bounds | Not applicable |
| Valgrind memcheck, every program | No errors, no leaks | No errors, no leaks | Not applicable |
| 8 deliberate mistakes injected into the order library | 8 of 8 caught | 8 of 8 caught | Not run |
| Windows build cross-compiled with MinGW-w64, warnings as errors | Passed (C11 and C17) | Not run | Not applicable |
Underlying type of enum color | Unsigned: unsigned int (GCC and Clang) | unsigned int (GCC and Clang) | Signed: (enum color)-1 reads back as −1. _Generic matched no integer type |
Not covered: macOS, embedded compilers (where -fshort-enums is sometimes the default), and C23 on MSVC.



