Expert C Programming

(Jeff_L) #1

Difference Between typedef int x[10] and #define x int[10]


As mentioned above, there is a key difference between a typedef and macro text replacement. The
right way to think about this is 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.


What typedef struct foo { ... foo; } foo; Means


There are multiple namespaces in C:




  • label names




  • tags (one namespace for all structs, enums and unions)




  • member names (each struct or union has its own namespace)




  • everyting else



Free download pdf