typedef and enum
- C course
- Intermediate
- Lesson 110/116
- 5 min
Learn enum types with typedef.
typedef and enum
An enum defines named integer constants. With typedef, you use a short name without repeating the enum keyword.
Example: typedef enum { RED, GREEN, BLUE } Color;. This defines three color constants (RED=0, GREEN=1, BLUE=2) and the type name Color. From then on you write Color c = GREEN; instead of enum Color c = GREEN;. This both shortens code and improves type safety. In a switch, you match each constant to a case; the color names make the code readable.
The color name function
To convert a Color value to a human-readable string, you write a function using switch. Each case matches a constant and returns its name.
Example: const char *color_name(Color c) { switch (c) { case RED: return "red"; case GREEN: return "green"; case BLUE: return "blue"; default: return "unknown"; } }. This function turns the numeric value into a meaningful string. printf("%s\n", color_name(GREEN)); prints "green". The switch structure extends easily when new colors are added; you just add a new case. This is the standard pattern for mapping enums to strings.
Practice Write a typedef enum program
Define typedef enum { RED, GREEN, BLUE } Color;. Write const char *color_name(Color c) using switch: RED→"kırmızı", GREEN→"yeşil", BLUE→"mavi", default→"bilinmeyen". In main print with printf("%s\n", color_name(GREEN));.
Starter code
#include <stdio.h>
// Define the Color enum with typedef
// Write color_name function with switch
// Call color_name(GREEN) in main and print
int main(void) {
return 0;
}Sample solution
#include <stdio.h>
typedef enum { RED, GREEN, BLUE } Color;
const char *color_name(Color c) {
switch (c) {
case RED: return "kırmızı";
case GREEN: return "yeşil";
case BLUE: return "mavi";
default: return "bilinmeyen";
}
}
int main(void) {
printf("%s\n", color_name(GREEN));
return 0;
}Expected output
yeşil
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the color constants
| Term | Meaning |
|---|---|
RED |
Zero |
GREEN |
One |
BLUE |
Two |
Color |
Type name |
2 Complete the color_name call
printf("%s
", color_name(____));
printf("%s
", color_name(GREEN));
Explanation: color_name(GREEN) returns "yeşil".
3 What does the color_name function return?
- Color components
- A color code (integer)
- A color name (string) Correct answer
- A memory address
Explanation: color_name converts a Color value to a string.