C
Summary - Advanced typedef
Combine struct, fp and opaque types to write a module interface.
typedef summary
In this summary you'll combine typedef enum, typedef struct and typedef function pointer into one program. The program contains a task struct and a function pointer that prints it.
The structure: you define priority levels with a Priority enum. A Task struct carries a name and priority. A TaskPrinter function pointer is assigned to the printing function. main creates a task and prints it through the pointer. This combines the three core uses of typedef in one program: constants with enum, data with struct, behavior abstraction with function pointer.
Exercise Write the typedef summary program
Define typedef enum { LOW, MEDIUM, HIGH } Priority;. Define typedef struct { char name[32]; Priority priority; } Task;. Define typedef void (*TaskPrinter)(const Task *);. Write void print_task(const Task *t) using const char *prio[] = {"düşük", "orta", "yüksek"}; and printf("%s [%s]\n", t->name, prio[t->priority]);. In main write Task t = {"Yedekle", HIGH}; TaskPrinter printer = print_task; printer(&t);.
Show example solution
#include <stdio.h>
typedef enum { LOW, MEDIUM, HIGH } Priority;
typedef struct {
char name[32];
Priority priority;
} Task;
typedef void (*TaskPrinter)(const Task *);
void print_task(const Task *t) {
const char *prio[] = {"düşük", "orta", "yüksek"};
printf("%s [%s]\n", t->name, prio[t->priority]);
}
int main(void) {
Task t = {"Yedekle", HIGH};
TaskPrinter printer = print_task;
printer(&t);
return 0;
}
Summary
In this group you learned advanced typedef uses. You saw typedef struct, typedef function pointer, typedef array, opaque types and typedef enum. You combined them to use enum, struct and function pointer in one program.
typedef is the core abstraction tool in C. Short type names make code readable; opaque types hide internals. In the next group the intermediate final project awaits; there you'll combine struct, linked list, function pointer and file I/O. Solid typedef skill is an inseparable part of clean C code.
Test yourself
-
What does typedef do?
- Gives a type a short name
- Allocates memory
- Sets up a loop
- Opens a file
Show answer
Gives a type a short name — typedef gives a type a new, short name.
-
Match the typedef uses
- typedef struct
- Data structure
- typedef enum
- Named constants
- typedef fp
- Behavior abstraction
- opaque
- Hidden internals
Next lesson: Project design