Enums
An enum
(short for enumeration) is a user-defined data type in C that consists of integral constants. It provides a way to define a set of named integer constants, making code more readable and maintainable by replacing numeric literals with descriptive identifiers.
Enums are particularly useful when a variable should only take one value from a limited set of possible values. Common use cases include representing states, flags, options, or any scenario where a variable can have only one value from a specific list of related values.
Syntax
enum enum_name {
const1,
const2,
...,
constN
};
Parameters:
enum_name
: Optional name for the enumeration typeconst1, const2, ..., constN
: Comma-separated list of enumerator identifiers
By default, enum values are assigned incrementing integer values starting from 0. However, custom values can be explicitly assigned to enumerators.
Return value:
Enum declarations do not return a value but define a new data type that can be used to declare variables.
Example 1: Defining and Using a Basic Enum Example
This example demonstrates how to define and use a basic enum for representing weekdays:
#include <stdio.h>// Define an enum for days of the weekenum Weekday {MONDAY, // 0TUESDAY, // 1WEDNESDAY, // 2THURSDAY, // 3FRIDAY, // 4SATURDAY, // 5SUNDAY // 6};int main() {// Declare a variable of enum typeenum Weekday today = WEDNESDAY;// Use the enum in a conditionif (today == WEDNESDAY) {printf("It's the middle of the week!\n");}// Print the enum valueprintf("Today is day %d of the week.\n", today);return 0;}
The output of this code is:
It's the middle of the week!Today is day 2 of the week.
This example creates an enum called Weekday
with seven enumerators representing days of the week. Note that enumerators are automatically assigned values starting from 0, though these values can be customized.
Example 2: Custom Enum Values
This example demonstrates assigning custom values to enum constants and handling them using a switch
statement for better readability and control flow.
#include <stdio.h>// Define an enum for HTTP status codes with custom valuesenum HttpStatus {OK = 200,CREATED = 201,BAD_REQUEST = 400,UNAUTHORIZED = 401,FORBIDDEN = 403,NOT_FOUND = 404,SERVER_ERROR = 500};void handleResponse(enum HttpStatus status) {switch(status) {case OK:printf("Request successful!\n");break;case CREATED:printf("Resource created successfully!\n");break;case BAD_REQUEST:case UNAUTHORIZED:case FORBIDDEN:case NOT_FOUND:printf("Client error: %d\n", status);break;case SERVER_ERROR:printf("Server error: %d\n", status);break;default:printf("Unknown status code: %d\n", status);}}int main() {// Simulate different HTTP responsesenum HttpStatus response1 = OK;enum HttpStatus response2 = NOT_FOUND;enum HttpStatus response3 = SERVER_ERROR;handleResponse(response1); // 200handleResponse(response2); // 404handleResponse(response3); // 500return 0;}
The output generated by this code is as follows:
Request successful!Client error: 404Server error: 500
This example demonstrates how enums with custom values can make code more intuitive when working with standardized codes. By assigning specific values to enum constants, we create meaningful identifiers for HTTP status codes that match their actual numeric values.
Example 3: Using Enums for Menu Options
This example demonstrates a simpler use case of enums for representing menu options in a program:
#include <stdio.h>// Define an enum for user actionsenum UserAction {ACTION_LOGIN,ACTION_LOGOUT,ACTION_VIEW_PROFILE,ACTION_EDIT_PROFILE,ACTION_COUNT // Total number of actions};// Define functions corresponding to each actionvoid login() {printf("User logged in.\n");}void logout() {printf("User logged out.\n");}void viewProfile() {printf("Displaying user profile.\n");}void editProfile() {printf("Editing user profile.\n");}int main() {// Array of function pointers corresponding to user actionsvoid (*actionHandlers[ACTION_COUNT])() = {login,logout,viewProfile,editProfile};// Simulate user selecting an actionenum UserAction selectedAction = ACTION_VIEW_PROFILE;// Invoke the corresponding function without using switch or ifif (selectedAction >= 0 && selectedAction < ACTION_COUNT) {actionHandlers[selectedAction]();} else {printf("Invalid action selected.\n");}return 0;}
The output of the code above will be:
Displaying user profile.
In this example, each enum constant represents a user action, and the actionHandlers
array maps these constants to their corresponding functions. By indexing into the array with the enum value, the appropriate function is called directly.
FAQs
1. What is the difference between macros and enums in C?
Macros (created with `#define`) and enums both can be used to define constants, but they have key differences:
- Enums are actual types, while macros are simple text replacements
- Enums provide type checking, whereas macros don't
- Enums are visible in debuggers, while macros are replaced before compilation
- Enums belong to a specific scope, while macros exist from their definition until the end of the file or until `#undef`
- Multiple related constants are grouped together in enums, while macros stand alone
2. What is the difference between arrays and enums in C?
Arrays and enums serve completely different purposes:
- Arrays store collections of elements of the same type that are accessed by index
- Enums define a set of named constants of integer type
- Arrays occupy memory to store values, whereas enums don't require storage (they're compile-time constants)
- Array elements are accessed using indices, while enum constants are used directly by name
3. How does memory allocation work with enums?
Enum variables typically have the same memory size as an `int` on the system (usually 4 bytes on modern systems), regardless of how many enumerators are defined. This is because an enum variable needs to store only one value from the set of possible enumeration constants. The enum constants themselves don't occupy any memory during program execution, as they're replaced with their integer values by the compiler.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.