C ยท Chapter 32 of 45

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.

Syntax
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.

Example 1 (c)
#include <stdio.h>

enum Day { MON, TUE, WED };

int main() {
  enum Day today = TUE;
  printf("%d\n", today);
  return 0;
}
Output
1

TUE is the second constant, so its default value is 1.

Example 2 (c)
#include <stdio.h>

enum Status { OK = 200, NOT_FOUND = 404 };

int main() {
  enum Status s = NOT_FOUND;
  printf("%d\n", s);
  return 0;
}
Output
404

Enum 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.
๐Ÿ’ก Note: Enums are internally just integers, so they don't provide the strict type safety found in some other languages.

๐Ÿ“ Quick Quiz

1. What value does the first constant in an enum default to?

2. Can you assign a custom starting value to an enum constant?

3. What is the main benefit of using an enum?