typedef enum
- C course
- Intermediate
- Lesson 39/116
- 5 min
Learn to give an enum a new name with typedef.
typedef enum
typedef gives a type a new alias. With typedef enum you give an enum a short name; you no longer write the enum keyword every time.
Example: typedef enum { RED, GREEN, BLUE } Color;. From now on you can write Color c = GREEN;; no need for enum Color c = GREEN;. This shortens and cleans the code. It's common in headers; API types look simpler. typedef doesn't create a new type; it just adds a second name to an existing one.
Using typedef
After using typedef enum, you declare variables without the enum keyword. This improves readability especially for long enum names.
Example: typedef enum { LOW, MEDIUM, HIGH } Priority;. Then you can write Priority p = HIGH;. enum Priority p = HIGH; is still valid; but it's not needed. In API design, using typedef is a common standard; the user doesn't need to know the type is an enum. This hides implementation detail and makes future changes easier.
Practice Print two colors with typedef enum
Define typedef enum { RED, GREEN, BLUE } Color;. In main, write Color c = RED; and Color g = GREEN;. Print with printf("%d %d\n", c, g);.
Starter code
#include <stdio.h>
// Define Color with typedef enum (RED, GREEN, BLUE)
// In main assign RED to c, GREEN to g and print
int main(void) {
return 0;
}Sample solution
#include <stdio.h>
typedef enum { RED, GREEN, BLUE } Color;
int main(void) {
Color c = RED;
Color g = GREEN;
printf("%d %d\n", c, g);
return 0;
}Expected output
0 1
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Type name in typedef enum {RED, GREEN, BLUE} Color;?
- Color Correct answer
- RED
- enum Color
- typedef
Explanation: typedef makes Color an alias for the enum type.
2 Match the typedef forms
| Term | Meaning |
|---|---|
typedef enum {...} Color |
Type alias |
Color c |
Variable declaration |
enum Color c |
Long form |
RED, GREEN, BLUE |
Constant list |
3 Complete the typedef enum alias
typedef enum { RED, GREEN, BLUE } ____;
Color c = GREEN;
typedef enum { RED, GREEN, BLUE } Color;
Color c = GREEN;
Explanation: Color is the alias for the enum.