網頁

2011年1月8日 星期六

Typedef

Typedef in C language will be heavily used in firmware code. If you don't know it clearly, sometimes it is even difficult to understand the interview questions!

typedef vs macro

#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.

沒有留言:

張貼留言