typedef
is one of things that I can never look back from. Essentially, it allows to alias existing types in C and makes code much easier to read and write.
Take the following example as an instance.
struct my_struct {
int a;
char b;
}
void init_my_struct(struct my_struct* s, int a, char b);
Now, we alias the my_struct
to another value using typedef
.
typedef struct my_struct {
int a;
char b;
} my_struct_t;
void init_my_struct(my_struct_t* s, int a, char b);
Notice how much easier it is to follow code. You may also omit the initial name declaration of my_struct
but I personally prefer it since it gives static analysis tools more information about the struct as opposed to just an anonymous struct. The same may be used for any type, even enums
. But, I feel the best use of typedef
is aliasing pointers to functions.
typedef enum color {
COLOR_RED,
COLOR_GREEN,
COLOR_BLUE
} color_t;
void display_value(color_t display_color);
The syntax behind them is confusing and weird and stems partly from the notion of "declaration reflects use" but is still strange. Aliasing these behemoths to something much easier to the eye is always welcome.
typedef void (*ParseFunction)();
Top comments (0)