C Typedef
Structs group values under one name, and the full type name gets long to write. A typedef gives a type a shorter name.
A short name for int
Age now means int, so it holds a number like any int. The output is 30.
#include <stdio.h>
typedef int Age;
int main() {
Age years = 30;
printf("%d\n", years);
return 0;
}Short name for a struct
Point now names the struct, so no struct keyword is needed. The output shows the point (3, 4).
#include <stdio.h>
typedef struct Point {
int x;
int y;
} Point;
int main() {
Point p = {3, 4};
printf("(%d, %d)\n", p.x, p.y);
return 0;
}Short name for a student
Student now names the whole struct. The output shows Ada at 20, built with the short name alone.
#include <stdio.h>
typedef struct {
char name[20];
int age;
} Student;
int main() {
Student s1 = {"Ada", 20};
printf("%s is %d.\n", s1.name, s1.age);
return 0;
}Example
#include <stdio.h>
typedef struct {
char title[30];
int pages;
float price;
} Book;
int main() {
Book b1 = {"Sea Atlas", 180, 24.50f};
printf("%s\n", b1.title);
printf("Pages: %d\n", b1.pages);
printf("Price: %.2f\n", b1.price);
return 0;
}Key points
- typedef creates a new name for a type that already exists.
- typedef int Age; makes Age mean int.
- A typedef for a struct drops the word struct from later code.
- typedef struct Point { int x; int y; } Point; names the struct Point.
- After the typedef, Point p; creates a point.
- The new name is only a name. The type and its values stay the same.
- Use a short name when the full type name is long to write.
Book is a short name for a struct with a title, a page count, and a price. The output prints all three members, so the short name carries the whole struct.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does typedef do?