C Enumerated Types
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.
→ I wrote 17 books to help you become a better developer:
- C Handbook
- Command Line Handbook
- CSS Handbook
- Express Handbook
- Git Cheat Sheet
- Go Handbook
- HTML Handbook
- JS Handbook
- Laravel Handbook
- Next.js Handbook
- Node.js Handbook
- PHP Handbook
- Python Handbook
- React Handbook
- SQL Handbook
- Svelte Handbook
- Swift Handbook
Also, JOIN MY CODING BOOTCAMP, an amazing cohort course that will be a huge step up in your coding career - covering React, Next.js - next edition February 2025