Typedef
suggest changeIntroduction
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.
Syntax
- typedef existing_name alias_name;
Remarks
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:
typedefis limited to giving symbolic names to types only where as#definecan be used to define alias for values as well.typedefinterpretation is performed by the compiler whereas#definestatements are processed by the pre-processor.- Note that
#define cptr char *followed bycptr a, b;does not do the same astypedef char *cptr;followed bycptr a, b;. With the#define,bis a plaincharvariable, but it is also a pointer with thetypedef.