C Enums
Represent a closed set of integral states with names, not unexplained literals.
Enumerations give states readable names
An enum declares integral constants with domain-specific names. It makes control flow easier to read and lets you avoid unexplained literals such as 3 scattered through your program. Structures still hold related fields; enums name a closed set of states those records can occupy. Continue with records in C Structures.
enum OrderStatus {
ORDER_PENDING,
ORDER_PAID,
ORDER_SHIPPED,
ORDER_CANCELLED,
};
const char *status_label(enum OrderStatus status) {
switch (status) {
case ORDER_PENDING: return "pending";
case ORDER_PAID: return "paid";
case ORDER_SHIPPED: return "shipped";
case ORDER_CANCELLED: return "cancelled";
default: return "invalid status";
}
}Run a named state instead of a magic number
The runner validates the declared ConnectionState names and reports the active enum constant with its current ordinal.
Edit the model, predict the result, then run it.
Default values start at zero; names are the contract
The default underlying values begin at zero and increase by one, but your code should rely on named constants—not their current numbers. Assign explicit values only when an external format, protocol, or stored data contract requires stable numeric codes. Reordering members without explicit values will change those numbers.
switch is a natural match for a closed set
A switch on an enum lists each named state. Include break after each case unless you intentionally fall through and comment that decision. C does not require switch to be exhaustive the way some languages do, so a missing case is a logic bug, not a compile error on every compiler.
An enum does not make invalid bytes impossible
C can still receive an unexpected value from a file, network packet, cast, or uninitialized object. Keep a default branch when input can cross a trust boundary, and make the recovery behavior intentional. Enums are often used as the tag beside a union; that tagged-union pattern is taught with structures.
Independent lab: label every state
Declare an enum for a task status, write a function that returns a string label for each name, and include default. Compile locally. Then reorder two members without explicit values and confirm that code comparing names still compiles while any code comparing raw numbers would silently change meaning.
Lesson review
- An enum names a closed set of integral constants.
- Compare enumerator names, not assumed ordinals, unless a protocol documents the numbers.
switchplusdefaulthandles named states and unexpected values.- Enums do not reject invalid stored integers by themselves.