The typedef
mechanism allows the creation of aliases for other types. It does not create new types. People often use typedef
to improve the portability of code, to give aliases to structure or union types, or to create aliases for function (or function pointer) types.
In the C standard, typedef
is classified as a 'storage class' for convenience; it occurs syntactically where storage classes such as static
or extern
could appear.
Disadvantages of Typedef
typedef
could lead to the pollution of namespace in large C programs.
Disadvantages of Typedef Structs
Also, typedef
'd structs without a tag name are a major cause of needless imposition of ordering relationships among header files.
Consider:
#ifndef FOO_H
#define FOO_H 1
#define FOO_DEF (0xDEADBABE)
struct bar; /* forward declaration, defined in bar.h*/
struct foo {
struct bar *bar;
};
#endif
With such a definition, not using typedefs
, it is possible for a compilation unit to include foo.h
to get at the FOO_DEF
definition. If it doesn't attempt to dereference the bar
member of the foo
struct then there will be no need to include the bar.h
file.
Typedef vs #define
#define
is a C pre-processor directive which is also used to define the aliases for various data types similar to typedef
but with the following differences:
typedef
is limited to giving symbolic names to types only where as #define
can be used to define alias for values as well.
typedef
interpretation is performed by the compiler whereas #define
statements are processed by the pre-processor.
Note that #define cptr char *
followed by cptr a, b;
does not do the same as typedef char *cptr;
followed by cptr a, b;
. With the #define
, b
is a plain char
variable, but it is also a pointer with the typedef
.