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.
Lessons in this unit:
| 0: | Introduction |
| 1: | Input and output |
| 2: | Variable scope |
| 3: | Static variables |
| 4: | Global variables |
| 5: | Type definitions |
| 6: | ▶︎ Enumerations |
| 7: | Structures |
| 8: | Command line parameters |
| 9: | Header files |
| 10: | The preprocessor |
| 11: | NULL values |
| 12: | Boolean values |
| 13: | Nesting functions |
| 14: | Conversion specifiers |
| 15: | Using quotes |
| 16: | String length |
| 17: | Returning strings |
| 18: | Array length |
| 19: | Looping through arrays |
| 20: | Checking character values |
| 21: | Printing percentage signs |
| 22: | Troubleshooting: Implicit function declarations |