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.

Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching Summer 2024. Join the waiting list!
→ Get my C Handbook

Here is how can I help you: