Wednesday, 5 December 2012

Worth Read #18

Typedef 
Typedef is frequently used in C to declare synonyms for pre-existing data types. It is also possible to use the preprocessor to do something similar. For instance, consider the following code fragment: 

#define dPS struct s *
typedef struct s * tPS;
The intent in both cases is to define dPS and tPS to be pointers to structure s. Which method, if any, is preferred and why?
This is a very subtle question, and anyone who gets it right (for the right reason) is to be congratulated or condemned ("get a life" springs to mind). The answer is the typedef is preferred. Consider the declarations:

dPS p1,p2;
tPS p3,p4;
The first expands to:

struct s * p1, p2;
which defines p1 to be a pointer to the structure and p2 to be an actual structure, which is probably not what you wanted. The second example correctly defines p3 and p4 to be pointers.

No comments:

Post a Comment