C Language | Structure Declarations | Type Aliases - typedef
The typedef specifier defines an alias for an existing type. Aliases can simplify code, improve portability, and hide complex structure or pointer declarations.
Type Aliases
Use the following syntax:
typedef existing-type new-type-name;
For example:
typedef unsigned char BYTE;
BYTE is now an alias for unsigned char. This can improve portability when a program needs types with specific sizes. A platform-specific header can map aliases such as WORD or DWORD to the appropriate built-in types.
Code 1
#include <stdio.h>
typedef unsigned char BYTE;
typedef int DWORD;
struct Color { BYTE r , g , b; };
DWORD main() {
struct Color color = { 0xFF , 0xAA , 0xAA };
printf("R = %d : G = %d : B = %d\n" , color.r , color.g , color.b);
return 0;
}
An alias does not create a distinct underlying type. BYTE and DWORD remain aliases for ordinary C types.
Pointer aliases are also possible:
typedef char STR , *PSTR;
This defines STR as char and PSTR as char *.
Code 2
#include <stdio.h>
typedef char STR , *PSTR;
int main() {
STR str[] = "Kitty on your lap";
PSTR pstr = str;
printf("%s\n" , pstr);
return 0;
}
Structure Aliases
Aliases are especially useful for structures because they avoid repeating the struct keyword.
struct tag_Point { int x , y; };
typedef struct tag_Point Point;
If the structure tag is not needed later, define an anonymous structure and its alias together.
typedef struct { int x , y; } Point;
Code 3
#include <stdio.h>
typedef struct { int x , y; } Point;
int main() {
Point po = { 200 , 50 };
printf("X = %d : Y = %d\n" , po.x , po.y);
return 0;
}
The same approach works for unions.
Function Types and Aliases
Functions also have types determined by their return type and parameter list. Two independently implemented functions with the same signature have the same function type.
Use this syntax to create an alias for a function type:
typedef return-type new-type-name(parameter-list);
Code 4
#include <stdio.h>
typedef void TEXTOUT(char *str);
TEXTOUT println;
int main() {
println("Kitty on your lap");
return 0;
}
void println(char *str) {
printf("%s\n" , str);
}
TEXTOUT println; is equivalent to declaring void println(char *str);.