Skip to content

C Enumerated Types

New Course Coming Soon:

Get Really Good at Git

An introduction to C Enumerated Types

Using the typedef and enum keywords we can define a type that can have either one value or another.

It’s one of the most important uses of the typedef keyword.

This is the syntax of an enumerated type:

typedef enum {
  //...values
} TYPENAME;

The enumerated type we create is usually, by convention, uppercase.

Here is a simple example:

typedef enum {
  true,
  false
} BOOLEAN;

C comes with a bool type, so this example is not really practical, but you get the idea.

Another example is to define weekdays:

typedef enum {
  monday,
  tuesday,
  wednesday,
  thursday,
  friday,
  saturday,
  sunday
} WEEKDAY;

Here’s a simple program that uses this enumerated type:

#include <stdio.h>

typedef enum {
  monday,
  tuesday,
  wednesday,
  thursday,
  friday,
  saturday,
  sunday
} WEEKDAY;

int main(void) {
  WEEKDAY day = monday;

  if (day == monday) {
    printf("It's monday!");
  } else {
    printf("It's not monday");
  }
}

Every item in the enum definition is paired to an integer, internally. So in this example monday is 0, tuesday is 1 and so on.

This means the conditional could have been if (day == 0) instead of if (day == monday), but it’s way simpler for us humans to reason with names rather than numbers, so it’s a very convenient syntax.

→ Get my C Handbook

Here is how can I help you: