'typedef' is a powerful tool for creating new names (aliases) for types, which makes the code shorter and easier to maintain and understand. The keyword appeared in early versions of C, simplifying life for developers of large projects, when long declarations of structures and pointers made the code unreadable and hard to maintain.
Originally, structures and unions were defined using long declarations with the keywords struct, union, enum. As the code grew, such declarations became excessive and inconvenient, leading to the introduction of typedef to shorten and standardize types.
Typical mistakes are related to a misunderstanding of aliases, mixing typedef with structure declarations, anonymous structures, difficulties with pointer arrays, and undocumented naming conventions.
'typedef' allows giving short names to existing types — both basic and compound:
Example code:
typedef struct Point { int x, y; } Point; Point p1; // instead of 'struct Point p1;' typedef unsigned char byte; byte buffer[8];
Key features:
1. Can typedef create a "new type" that is incompatible with the base type (e.g., int)?
No. typedef only provides an alias. The type-at-the-compiler-level remains the same, casting is possible without compilation errors.
2. If you declare typedef struct {} name_t;, and then struct name_t var;, what is the result?
This is an error! After typedef struct MyStruct { ... } Name;, Name is used for variables, not struct Name. struct Name is unknown to the compiler — it doesn't work that way.
3. typedef int arr[10]; arr a,b; What is the type of a and b?
a and b are both arrays of int of length 10. They are not pointers! The error is expecting 'int* a, b' if forgetting about the characteristics of typedef with arrays and pointers.
In a project, typedef struct User { ... } User; is declared, but struct User my_user; is used — the compiler complains, the code is non-portable.
Pros:
Cons:
In the entire project, a single standard is adhered to: typedef struct {...} Name;, only using Name var; without struct.
Pros:
Cons: