Topics / C Programming / Q13
What is the difference between typedef and #define for creating type names?
Short answer: typedef creates a real alias for a type that the compiler understands, with normal scope rules. #define only replaces text, which breaks with pointer types and can surprise you in declarations. Use typedef for types.
typedef char *str_t;
#define STR_T char *
str_t a, b; /* a and b are both char * */
STR_T c, d; /* becomes "char * c, d;": c is char *, d is just char! */
Other differences
typedef |
#define |
|
|---|---|---|
| Processed by | compiler | preprocessor |
| Scope | block/file scope like any declaration | until #undef or end of file |
| Works with complex types (function pointers, arrays) | yes | fragile |
Can be combined with unsigned, etc. |
no (unsigned my_int is an error) |
yes (text) |
| Debugger shows the name | usually | no |
Readable function-pointer types (a very common use):
typedef void (*isr_t)(void);
isr_t vector_table[64]; /* array of 64 function pointers */
typedef int (*cmd_handler_t)(int argc, char **argv);
Struct typedefs:
typedef struct uart uart_t; /* opaque type: users cannot see inside */
uart_t *uart_open(int port);
Opaque types like this are good encapsulation in C: the struct is only defined in uart.c.
Style notes: names ending in _t are reserved by POSIX for its own types, so some projects avoid that suffix; and hiding a pointer inside a typedef (typedef struct x *xptr;) is discouraged by many style guides (including Linux), because it hides that the value is a pointer.