typedef struct
- C course
- Beginner
- Lesson 96/116
- 5 min
Learn to give a struct a new name with typedef.
typedef struct: a short name
typedef gives a type another name. When used with struct you can declare variables without repeating the struct keyword.
typedef struct {
int x;
int y;
} Point;
Point p = {3, 4};Here Point is now a type name; you do not need to write struct Point. This simplifies code, especially with long struct names. You give a name to an anonymous struct; moving the definition to other files also becomes easier.
Using typedef
After typedef declaring variables is shorter. You use only the name, without writing struct.
typedef struct {
char name[32];
int age;
} Person;
Person a;
Person b = {"Ayse", 25};Here Person a and Person b = {...} look much cleaner. Member access still uses .: b.age. This form is very common in real projects; almost every struct is declared with typedef.
Practice Print coordinates with typedef Point
Use typedef struct to define a type named Point with int x and int y members. In main create a variable Point p = {7, 8} and print its members with printf.
Starter code
#include <stdio.h>
/* Use typedef to define a struct named Point (int x, int y) */
int main(void) {
/* Create a Point; print it with printf */
return 0;
}Sample solution
typedef struct { int x; int y; } Point;
Point p = {7, 8};
printf("%d %d\n", p.x, p.y);Expected output
7 8
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Fill in the blank: typedef definition
____ struct {
int x;
int y;
} Point;
typedef struct {
int x;
int y;
} Point;
Explanation: typedef gives a short name to a struct.
2 Match declaration to equivalent
| Term | Meaning |
|---|---|
typedef struct {...} Point; |
Gives a type name |
Point p; |
Declaration without struct |
struct Point p; |
Long form |
p.x |
Member access |
3 How is a variable declared after a typedef struct definition?
- Point p; Correct answer
- struct Point p;
- typedef Point p;
- new Point p;
Explanation: After typedef you write only Point p;