Chapter 17Beginner

Enumerations in C

Create named constants for better code readability. Instead of using 0, 1, 2 for days, use MON, TUE, WED with enums.

12 min readUpdated 2024-12-16
enumenumerationnamed constantsswitchtypedef enum

What You Will Learn

  • Declare enumerations
  • Set custom enum values
  • Use enums with switch statements
  • Make code more readable with enums

01What is an Enumeration?

An enumeration (enum) is a user-defined type that consists of a set of named integer constants. It makes your code more readable by giving meaningful names to numeric values.

Why Use Enums?

❌ Without Enums (Magic Numbers)
main.c
C
int status = 0; // What does 0 mean?
if (status == 1) { /* success? error? */ }
if (status == 2) { /* pending? */ }

Hard to understand and maintain

✓ With Enums (Named Constants)
main.c
C
enum Status status = SUCCESS;
if (status == ERROR) { /* clear! */ }
if (status == PENDING) { /* obvious! */ }

Self-documenting code

Common Use Cases

  • • Days of the week (MONDAY, TUESDAY, ...)
  • • Status codes (SUCCESS, ERROR, PENDING)
  • • Directions (NORTH, SOUTH, EAST, WEST)
  • • Colors (RED, GREEN, BLUE)
  • • Menu options, game states, modes...

02Declaring Enumerations

enum_basic.c
C
1#include <stdio.h>
2
3// Define an enumeration
4enum Day {
5 SUNDAY, // = 0 (default, starts at 0)
6 MONDAY, // = 1
7 TUESDAY, // = 2
8 WEDNESDAY, // = 3
9 THURSDAY, // = 4
10 FRIDAY, // = 5
11 SATURDAY // = 6
12};
13
14int main() {
15 // Declare an enum variable
16 enum Day today = WEDNESDAY;
17 enum Day tomorrow = THURSDAY;
18
19 printf("Today is day number: %d\n", today); // 3
20 printf("Tomorrow is day number: %d\n", tomorrow); // 4
21
22 // Can use in conditions
23 if (today == WEDNESDAY) {
24 printf("It's Wednesday!\n");
25 }
26
27 // Enums are integers - can do arithmetic (not recommended)
28 enum Day nextDay = today + 1;
29 printf("Next day number: %d\n", nextDay); // 4
30
31 return 0;
32}

Output:

Today is day number: 3
Tomorrow is day number: 4
It's Wednesday!
Next day number: 4

🔍 How This Program Works

1

enum Day {...} — Defines 7 named constants. SUNDAY=0, MONDAY=1, ..., SATURDAY=6 (auto-increments from 0).

2

enum Day today = WEDNESDAY — Creates variable and assigns WEDNESDAY (which equals 3).

3

printf("%d", today) — Prints 3, because internally WEDNESDAY is stored as the integer 3.

4

today == WEDNESDAY — Compares integers: 3 == 3 is true! Much more readable than today == 3.

5

today + 1 — Since enums are integers, arithmetic works: 3 + 1 = 4 (THURSDAY).

Default Values

By default, the first enum constant is 0, and each subsequent constant is previous + 1.

03Custom Enum Values

You can assign specific integer values to enum constants:

enum_custom.c
C
1#include <stdio.h>
2
3// Custom starting value
4enum Month {
5 JANUARY = 1, // Start at 1 instead of 0
6 FEBRUARY, // = 2 (auto-increments)
7 MARCH, // = 3
8 APRIL, // = 4
9 // ... etc
10 DECEMBER = 12
11};
12
13// Arbitrary values (like bit flags)
14enum Permission {
15 READ = 1, // 0001 in binary
16 WRITE = 2, // 0010
17 EXECUTE = 4, // 0100
18 DELETE = 8 // 1000
19};
20
21// HTTP status codes
22enum HttpStatus {
23 OK = 200,
24 CREATED = 201,
25 BAD_REQUEST = 400,
26 UNAUTHORIZED = 401,
27 NOT_FOUND = 404,
28 SERVER_ERROR = 500
29};
30
31int main() {
32 enum Month currentMonth = MARCH;
33 printf("Month number: %d\n", currentMonth); // 3
34
35 // Combine permissions with bitwise OR
36 int userPerms = READ | WRITE; // 3 (0011)
37 printf("User permissions: %d\n", userPerms);
38
39 // Check permission with bitwise AND
40 if (userPerms & WRITE) {
41 printf("User can write!\n");
42 }
43
44 enum HttpStatus response = NOT_FOUND;
45 printf("HTTP Status: %d\n", response); // 404
46
47 return 0;
48}

Enum Value Rules

  • • First constant defaults to 0 if not specified
  • • Each subsequent constant is previous + 1
  • • You can assign any integer value
  • • Multiple constants can have the same value (aliases)
  • • Values can be negative
enum_aliases.c
C
1// Same values (aliases)
2enum Boolean {
3 FALSE = 0,
4 TRUE = 1,
5 NO = 0, // Same as FALSE
6 YES = 1 // Same as TRUE
7};
8
9// Negative values
10enum Temperature {
11 FREEZING = -10,
12 COLD = 0,
13 WARM = 20,
14 HOT = 35
15};

04Enums with switch Statements

Enums work perfectly with switch statements, making your code clean and readable:

enum_switch.c
C
1#include <stdio.h>
2
3enum TrafficLight {
4 RED,
5 YELLOW,
6 GREEN
7};
8
9const char* getAction(enum TrafficLight light) {
10 switch (light) {
11 case RED:
12 return "STOP!";
13 case YELLOW:
14 return "SLOW DOWN";
15 case GREEN:
16 return "GO";
17 default:
18 return "UNKNOWN";
19 }
20}
21
22int main() {
23 enum TrafficLight current = RED;
24
25 printf("Light is RED: %s\n", getAction(RED));
26 printf("Light is YELLOW: %s\n", getAction(YELLOW));
27 printf("Light is GREEN: %s\n", getAction(GREEN));
28
29 // Simulate light change
30 for (int i = 0; i < 6; i++) {
31 printf("\nCycle %d: ", i + 1);
32 current = i % 3; // Cycles through 0, 1, 2
33 printf("%s", getAction(current));
34 }
35 printf("\n");
36
37 return 0;
38}

Output:

Light is RED: STOP!
Light is YELLOW: SLOW DOWN
Light is GREEN: GO

Cycle 1: STOP!
Cycle 2: SLOW DOWN
Cycle 3: GO
Cycle 4: STOP!
Cycle 5: SLOW DOWN
Cycle 6: GO

05typedef with Enums

Use typedef to create shorter type names (avoid writing enum every time):

Without typedef

main.c
C
enum Status { OK, ERROR };
enum Status result; // Must write "enum" every time

With typedef ✓

main.c
C
typedef enum { OK, ERROR } Status;
Status result; // Cleaner!
enum_typedef.c
C
1#include <stdio.h>
2
3// Method 1: typedef after enum
4enum _Direction { NORTH, SOUTH, EAST, WEST };
5typedef enum _Direction Direction;
6
7// Method 2: typedef inline (preferred)
8typedef enum {
9 LOW,
10 MEDIUM,
11 HIGH,
12 CRITICAL
13} Priority;
14
15int main() {
16 Direction heading = NORTH;
17 Priority level = HIGH;
18
19 printf("Heading: %d, Priority: %d\n", heading, level);
20
21 return 0;
22}

06Enum Memory Size

In C, enums are stored as integers. The size is typically sizeof(int) = 4 bytes.

enum_size.c
C
1#include <stdio.h>
2
3typedef enum { A, B, C } SimpleEnum;
4typedef enum { X = 1000000000 } LargeEnum;
5
6int main() {
7 printf("Size of int: %zu bytes\n", sizeof(int));
8 printf("Size of SimpleEnum: %zu bytes\n", sizeof(SimpleEnum));
9 printf("Size of LargeEnum: %zu bytes\n", sizeof(LargeEnum));
10
11 // Enum variable size
12 SimpleEnum e = A;
13 printf("Size of enum variable: %zu bytes\n", sizeof(e));
14
15 return 0;
16}

Typical Output:

Size of int: 4 bytes
Size of SimpleEnum: 4 bytes
Size of LargeEnum: 4 bytes
Size of enum variable: 4 bytes

Note

Unlike some other languages, C enums always use at least sizeof(int) bytes, even if you only have 2-3 values. The compiler doesn't optimize the size.

07Best Practices

✓ Use UPPERCASE for enum constants

main.c
C
enum Color { RED, GREEN, BLUE }; // Good - clear constants
enum color { red, green, blue }; // Works, but less conventional

✓ Add a COUNT constant for iteration

main.c
C
typedef enum {
APPLE,
BANANA,
ORANGE,
FRUIT_COUNT // = 3, useful for loops/arrays
} Fruit;
const char* fruitNames[FRUIT_COUNT] = {"Apple", "Banana", "Orange"};

✓ Add prefix to avoid naming conflicts

main.c
C
// Without prefix - might conflict with other code
enum { RED, GREEN, BLUE };
// With prefix - safer
enum Color { COLOR_RED, COLOR_GREEN, COLOR_BLUE };
enum State { STATE_IDLE, STATE_RUNNING, STATE_STOPPED };

❌ Don't assume enum values

main.c
C
// BAD: Assuming values
if (day >= 0 && day <= 6) { /* risky */ }
// GOOD: Use the actual constants
if (day >= SUNDAY && day <= SATURDAY) { /* safe */ }

08Summary

What You Learned:

  • Enum: Named integer constants for readable code
  • Default values: Start at 0, auto-increment by 1
  • Custom values: Assign any integer value
  • switch: Enums work great with switch statements
  • typedef: Create shorter type names
  • Size: Same as int (typically 4 bytes)

09Next Steps

You've completed all derived data types! Continue with: