C Enums
An enum (enumeration) is a user-defined type that assigns readable names to a set of integer constants. This makes code more descriptive than using plain 'magic numbers'.
By default, enum values start at 0 and increase by 1 for each subsequent name, but you can explicitly assign specific integer values.
enum Name { CONST1, CONST2, CONST3 };Defining an enum
An enum is declared with the `enum` keyword followed by a name and a list of constants in braces, like `enum Day { MON, TUE, WED };`. MON is 0, TUE is 1, and so on by default.
Custom values
You can assign specific values to some or all enum constants, and subsequent unassigned constants continue counting up from the last assigned value.
#include <stdio.h>
enum Day { MON, TUE, WED };
int main() {
enum Day today = TUE;
printf("%d\n", today);
return 0;
}1TUE is the second constant, so its default value is 1.
#include <stdio.h>
enum Status { OK = 200, NOT_FOUND = 404 };
int main() {
enum Status s = NOT_FOUND;
printf("%d\n", s);
return 0;
}404Enum constants can be given explicit custom integer values.
Key points
- enum creates named integer constants for readability.
- By default, values start at 0 and increment by 1.
- You can explicitly assign custom values to enum constants.
- Enums make code more self-documenting than raw numbers.
