An enum in C, short for enumeration, is a type whose named constants represent related integer values. It lets you write names such as STATE_READY instead of scattering unexplained numbers throughout a program, making code easier to read and maintain.
What an enum represents
An enumeration groups a set of named integer constants under an enum type. It is useful when a variable is expected to represent one of a small number of meaningful choices: a program state, a menu selection, a direction, or an error category. The names describe the choices; the associated values are integers.
For example, enum State can describe whether a task is waiting, running, or finished. The compiler still treats enum values as integer-based values, so an enum is not a string type and does not automatically restrict a variable to only the named choices. That distinction matters when validating input or handling data from outside the program.
Enums are part of standard C, rather than a feature limited to a particular compiler or operating system. Their exact representation, however, is not generally fixed by the language in the way a programmer might assume. Understanding both the convenience and the limits of an enum helps you use one appropriately.
Declaring an enum in C
A basic declaration lists the enum tag and its enumerators (the names for the individual values):
enum State {
STATE_WAITING,
STATE_RUNNING,
STATE_FINISHED
};
enum State current_state = STATE_WAITING;
State is the tag, and STATE_WAITING, STATE_RUNNING, and STATE_FINISHED are enumerator names. The declaration introduces the type enum State; the final line declares a variable of that type. The enum keyword is part of the type spelling when using a tag.
If you want a shorter type name, you can create a typedef:
typedef enum {
COLOR_RED,
COLOR_GREEN,
COLOR_BLUE
} Color;
Color selected = COLOR_GREEN;
Here, Color is a typedef name, so it can be used without writing enum. A typedef is an alias, not a separate kind of enum. Choose names that communicate their purpose; a project-wide prefix such as COLOR_ also helps avoid collisions because enumerator names share the ordinary identifier namespace with variables and functions.
You may also declare an enum type and a variable in the same declaration, but separating the type definition from variable declarations is often clearer, especially when several functions need to use the type.
Default values and explicitly assigned values
Unless you assign values yourself, the first enumerator has value zero and each following enumerator is one greater than the previous one. Thus, in the State example, the values are 0, 1, and 2. These are convenient defaults, but the names—not the particular numbers—should usually carry meaning in the code.
You can provide an explicit integer constant expression when a value needs to match a protocol, file format, or existing interface:
enum Response {
RESPONSE_OK = 200,
RESPONSE_NOT_FOUND = 404,
RESPONSE_ERROR = 500
};
If an enumerator after an explicitly valued one has no assignment, it receives the preceding value plus one. For instance, if one name is assigned 10, the next unnamed one is 11. Values do not have to be consecutive: explicit assignments can leave gaps or use negative values, provided the values meet the requirements of the C language version in use. In C17 and earlier, each enumerator value must be representable as an int.
Two enumerator names may be assigned the same value, but that can make code harder to interpret. In a switch, for example, two case labels with the same value are not allowed in the same switch statement. Use duplicate values only when they are intentional aliases and the surrounding code accounts for them.
Enum types, integer values, and storage
In C17 and earlier, an enum type is compatible with an implementation-defined integer type capable of representing all its enumerator values. The compiler chooses the compatible type; the C standard does not promise that every enum occupies the same number of bytes on every compiler or platform. The type may also differ between enum declarations, depending on their values and the implementation.
This means an enum is not a portable way to specify an exact storage width. Do not assume that an enum is always the size of an int, or that writing its raw bytes to a file or network connection creates a portable format. If an external format requires a particular width, use an appropriate fixed-width integer type from <stdint.h> and explicitly convert between that representation and the enum. Also define the numeric codes as part of the format rather than relying on declaration order.
Enum values are integer-based, but this does not mean every integer is a meaningful choice. C does not generally enforce a closed set of values whenever an enum variable is assigned. A value can arrive through a conversion, input parsing, or other computation that is not one of the listed names. Validate data at boundaries and provide a fallback path when unexpected values are possible.
For ordinary small enums, values can be used naturally in conditions and switch statements. When formatting one for output, consider printing a descriptive name with a switch rather than assuming that a numeric value is a useful message to a user. If you do print a number, make sure the conversion and format specifier match the value being printed.
Using enums in conditions and switch statements
Enums are especially useful when they make control flow self-explanatory. A function that returns a status enum, for example, can make its possible outcomes clearer than a function that returns undocumented numbers.
enum State {
STATE_WAITING,
STATE_RUNNING,
STATE_FINISHED
};
void report_state(enum State state)
{
switch (state) {
case STATE_WAITING:
/* Handle a waiting task. */
break;
case STATE_RUNNING:
/* Handle a running task. */
break;
case STATE_FINISHED:
/* Handle a finished task. */
break;
default:
/* Handle an unexpected value. */
break;
}
}
The default branch is useful when a value might come from untrusted input, a cast, or a later change to the program. If every enumerator is handled and the compiler warns about missing switch cases, that warning can help reveal omissions when the enum changes. Some teams omit default in carefully controlled switches for this reason; the right choice depends on whether unexpected values need explicit handling and on the project’s warning policy.
Enums can also clarify function interfaces and structure members. A parameter declared as enum State communicates more intent than a plain integer, even though C does not provide the strict type safety that some other languages associate with enumerations.
Enums compared with macros and constants
Before enums were commonly used for named integer choices, programmers often wrote preprocessor macros such as #define STATE_WAITING 0. Macros can still be appropriate for some purposes, but they are handled by the preprocessor: they have no enum type, and their names are replaced before the compiler analyzes the resulting C code. An enum keeps related constants in a language-level declaration and gives readers a visible group of choices.
A const int object is not simply interchangeable with an enumerator. It is an object with a type and storage rules, while an enumerator is an integer constant usable in contexts that require an integer constant expression. For example, an enumerator can be used as a case label. Choose the construct that fits the intended meaning: enums for named integer alternatives, macros for suitable preprocessing tasks, and typed objects when an actual object is needed.
Enums also differ from strings. If a program needs to display “Waiting” to a user, the enum itself does not produce that text. Map each value to a string explicitly, often through a function with a switch. That keeps the internal choice separate from the wording shown in an interface and makes it easier to change displayed text without changing numeric codes.
Common mistakes and practical safeguards
- Assuming the first value is one: The first enumerator is zero by default. If zero has a special meaning, name it clearly; if a different starting value is required, assign it explicitly.
- Using enum values as stable file codes by accident: Inserting or reordering implicit enumerators can change their numeric values. Assign explicit values when numbers are part of a persistent or external contract.
- Assuming an enum rejects invalid values: It does not act as automatic input validation. Check values read from files, command-line arguments, network messages, or other external sources.
- Expecting enum names to be strings: Names such as
STATE_RUNNINGare identifiers in source code, not text stored at runtime. Provide a conversion function if readable text is needed. - Using duplicate values without considering switches: A switch cannot contain two case labels with the same value. If aliases are needed, group their handling deliberately rather than adding duplicate cases.
- Relying on enum size or signedness: These are not portable assumptions in traditional C. Use a defined integer representation when binary layout or a fixed width matters.
Bit flags are another area that needs care. An enum can name individual powers of two, such as a read flag and a write flag, but combining flags with bitwise operators produces integer values and does not make the enum a dedicated set type. Keep flag values within the range supported by the chosen integer type, and use an explicitly chosen unsigned integer type when the representation or available bit width matters. Do not treat a conventional choice of enum values as a guarantee about the enum’s storage layout.
Choosing an enum design
Use an enum when the alternatives are conceptually related and readers benefit from seeing them together. Prefer clear, consistent names, and decide whether the numeric values are merely internal conveniences or part of a public contract. That decision determines whether implicit numbering is adequate or explicit assignments are safer.
When the enum is part of a public header or a library interface, consider compatibility. Changing an implicit value can affect callers that store, compare, or transmit the number. If the enum crosses a compiler, language, or system boundary, document the mapping and convert to a defined representation rather than assuming all participants make the same storage choices.
For an internal state variable, a simple enum with default sequential values is often a good fit. For a serialized format, a hardware register, or a protocol, explicit integer codes and validation are more important than brevity. For a large, changing collection of labels that is primarily textual, a lookup table or string-based representation may be more appropriate than an enum.
Frequently Asked Questions
What is the default value of the first enum constant in C?
The first enumerator has the value 0 unless you assign it another value. Each following enumerator without an explicit assignment is one greater than the value before it.
Are enums in C the same as enums in C++?
No. C and C++ have related enum syntax, but their type rules and features are not identical. In particular, do not assume C provides C++ features such as scoped enum class types; ordinary C enumerator names are in the surrounding identifier scope.
Can an enum variable contain a value not listed in its declaration?
C does not generally make an enum a runtime-validated closed set. Unexpected values can arise through conversions or external data, so check values when correctness depends on them and handle unexpected cases where appropriate.
Can I print an enum by using its name?
No. Enumerator names exist in the source code and are not automatically available as runtime strings. Use a function, often a switch, to map values to readable text.
Does an enum always use the same amount of memory as an int?
No. In C17 and earlier, the compatible integer type and resulting representation are implementation-defined. If an exact width is needed for a file, protocol, or hardware interface, use a suitable fixed-width integer type and convert explicitly.
Related
- Debt Payoff Tracker Excel Template: How to Build One
- Minimum in Excel: Find the Smallest Value in a Range
- Debt Payoff Excel Template: Free Options and Setup
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Excel Data Analysis ANOVA: Run and Interpret TestsTo run an ANOVA in Microsoft Excel for Microsoft 365 on Windows, enable the Analysis ToolPak, select Data…
- Quinceañera Budget Spreadsheet: Build a Clear PlanA quinceañera budget spreadsheet helps you list expected costs, record what you actually pay, and see whether the…
- How to Flip Tabs in Excel Using Keyboard ShortcutsTo flip between worksheet tabs in Excel for Microsoft 365 on Windows, press Ctrl+Page Up for the previous…
- Excel Table Data Validation: Setup and TroubleshootingTo add data validation to an Excel table, select its data cells, choose Data > Data Validation, and…
- How to Create a PowerPoint Template in Microsoft 365To create a PowerPoint template in Microsoft 365 for Windows, open a presentation, choose View > Slide Master,…
- Import Excel CSV Files in Python: A Step-by-Step GuideTo import a CSV file saved from Excel into Python, install pandas, then use import pandas as pd…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.