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.
Download my free C Handbook
More clang tutorials:
- Introduction to the C Programming Language
- C Variables and types
- C Constants
- C Operators
- C Conditionals
- How to work with loops in C
- Introduction to C Arrays
- How to determine the length of an array in C
- Introduction to C Strings
- How to find the length of a string in C
- Introduction to C Pointers
- Looping through an array with C
- Booleans in C
- Introduction to C Functions
- How to use NULL in C
- Basic I/O concepts in C
- Double quotes vs single quotes in C
- How to return a string from a C function
- How to solve the implicitly declaring library function warning in C
- How to check a character value in C
- How to print the percentage character using `printf()` in C
- C conversion specifiers and modifiers
- How to access the command line parameters in C
- Scope of variables in C
- Can you nest functions in C?
- Static variables in C
- C Global Variables
- The typedef keyword in C
- C Enumerated Types
- C Structures
- C Header Files
- The C Preprocessor