Nearby lessons

63 of 72

C - typedef

The typedef keyword gives an existing data type a new name. It is often used with structures to make declarations shorter and easier to read.

1. What Is typedef?

The typedef keyword gives another name to an existing data type. This new name can make code easier to read.

In simple words: typedef is like giving a short name to a type that already exists.

Example01
CCode Cell
1#include <stdio.h>
2 
3typedef unsigned int uint;
4 
5int main(void) {
6 uint age = 21;
7 uint students = 35;
8 
9 printf("Age: %u\n", age);
10 printf("Students: %u\n", students);
11 
12 return 0;
13}
Output
Age: 21
Students: 35

2. typedef with a Structure

Normally, in C, we declare a structure variable using the struct keyword. With typedef, we can give the structure a shorter name.

Example02
CCode Cell
1#include <stdio.h>
2 
3typedef struct {
4 int rollNo;
5 char name[30];
6 float marks;
7} Student;
8 
9int main(void) {
10 Student s1 = {101, "Rahul", 88.5f};
11 
12 printf("Roll Number: %d\n", s1.rollNo);
13 printf("Name: %s\n", s1.name);
14 printf("Marks: %.1f\n", s1.marks);
15 
16 return 0;
17}
Output
Roll Number: 101
Name: Rahul
Marks: 88.5

3. Without typedef vs With typedef

Both examples create a variable of a structure type. The second example is shorter because Book is the alias created using typedef.

Example03
CCode Cell
1/* Without typedef */
2struct Book {
3 char title[30];
4};
5 
6struct Book b1;
7 
8/* With typedef */
9typedef struct {
10 char title[30];
11} Book;
12 
13Book b2;
Output
Use struct Book b1; without a typedef alias.
Use Book b2; when the Book alias is defined with typedef.

4. typedef vs #define

typedef creates a type alias that the compiler understands. #define is a preprocessor instruction that replaces matching text before compilation.

  • Use typedef when you want to give a data type another name.
  • Use #define commonly for symbolic constants or simple text replacement.

Common Mistakes

  • Put the new name at the end of the typedef declaration.
  • Do not forget the semicolon at the end.
  • typedef int Marks; is still based on int; it does not make a separately enforced type.
  • Do not create unnecessary aliases if the original type is already clear.
📝 Key Takeaways
  • typedef creates an alias for an existing type; it does not create a completely new type.
  • Write typedef first, then the existing type, and finally the new name.
  • typedef can make structure variable declarations shorter.
  • A typedef declaration must end with a semicolon.

🧠 Test Your Knowledge

3 Questions
Progress: 0 / 3