Monday, July 02, 2007

Difference between typedef and #define

to view a typedef as being a complete "encapsulated" type—you can't add to it after you have declared it. The difference between this and macros shows up in two ways.

You can extend a macro typename with other type specifiers, but not a typedef 'd typename. That is,
#define peach int
unsigned peach i; /* works fine */
typedef int banana;
unsigned banana i; /* Bzzzt! illegal */

Second, a typedef 'd name provides the type for every declarator in a declaration.
#define int_ptr int *
int_ptr chalk, cheese;

After macro expansion, the second line effectively becomes:
int * chalk, cheese;

This makes chalk and cheese as different as chutney and chives: chalk is a pointer-to-an-integer, while cheese is an integer. In contrast, a typedef like this:

typedef char * char_ptr;
char_ptr Bentley, Rolls_Royce;

declares both Bentley and Rolls_Royce to be the same. The name on the front is different, but they are both a pointer to a char.

No comments:

Post a Comment