Q1 - what is the difference between #define and typedef
defines are handled by a preprocessor (a program run before the actual c compiler) which
works like replace all in you editor.
Typedef is handled by the c compiler itself, and is an actual definition of a new type.
Answer
The distinction given between #define and typedef has one significant error: typedef does
not in fact create a new type. According to Kernighan & Richie, the authors of the
authoritative and universally acclaimed book, "The C Programming Language":
It must be emphasized that a typedef declaration does not create a new type in any sense;
it merely adds a new name for some existing type. Nor are there any new semantics:
variables declared this way have exactly the same properties as variables whose
declarations are spelled out explicitly. In effect, typedef is like #define, except that
since it is interpreted by the compiler, it can cope with textual substitutions that are
beyond the capabilities of the preprocessor.
Answer
There are some more subtleties though. The type defined with a typedef is exactly like
its counterpart as far as its type declaring power is concerned BUT it cannot be modified
like its counterpart. For example, let's say you define a synonim for the int type with:
typedef int MYINT
Now you can declare an int variable either with
int a;
or
MYINT a;
But you cannot declare an unsigned int (using the unsigned modifier) with
unsigned MYINT a;
although
unsigned int a;
would be perfectly acceptable.
some things can be done with typedef that cannot be done with define.
Examples:
Code:
typedef int* int_p1;
int_p1 a, b, c; // a, b, and c are all int pointers.
#define int_p2 int*
int_p2 a, b, c; // only the first is a pointer!
No comments:
Post a Comment