typedef in C
As C programs grow larger, variable and data type names can become long, confusing, and hard to read.
The typedef keyword helps us create short, meaningful names for existing data types.
This improves code readability and makes programs easier to maintain.
What Is typedef?
typedef allows you to give a new name (alias) to an existing data type.
It does not create a new data type — it only creates a new name.
Why Do We Need typedef?
Look at this declaration:
unsigned long int totalDistance;
Now imagine using this many times.
Using typedef:
typedef unsigned long int ULI;
ULI totalDistance;
Same meaning — cleaner code.
Basic Syntax
typedef existing_type new_name;
Simple Example
typedef int Number;
Number a = 10;
Number b = 20;
Here, Number behaves exactly like int.
typedef with Structures
This is where typedef becomes extremely useful.
Without typedef:
struct Student {
int id;
float marks;
};
struct Student s1;
With typedef:
typedef struct {
int id;
float marks;
} Student;
Student s1;
Cleaner, simpler, and professional.
typedef with Pointers
Pointer declarations can get confusing.
typedef int* IntPtr;
IntPtr p, q;
Both p and q are pointers to integers.
Without typedef, this often causes mistakes.
Real-World Usage
In real projects, typedef is used for:
- Complex structures
- Platform-independent types
- Library design
- Readable APIs
Common Mistake
Assuming typedef creates a new data type.
It does not — it only creates an alias.
Mini Practice
- Create a typedef for
floatnamedMarks - Use it to store marks of 3 students
Quick Quiz
Q1. What does typedef do?
It creates an alias for an existing data type.
Q2. Does typedef create a new data type?
No.
Q3. Why is typedef useful with structures?
It removes repeated use of the struct keyword.
Q4. Can typedef be used with pointers?
Yes.
Q5. Is typedef commonly used in professional C projects?
Yes.