Nearby lessons
63 of 72C - 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
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
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
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
typedefwhen you want to give a data type another name. - Use
#definecommonly 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 onint; 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 QuestionsProgress: 0 / 3