The difference between typedef and define

Possible duplicate:
Is typedef and #define the same in c?
Confused by #define and typedef

Is there any difference between the following:

#define NUM int

...

NUM x;
x = 5;
printf("X: %d\n", x);

And this:

typedef int NUM;

...

NUM x;
x = 5;
printf("X : %d\n", x);

Both tests are assembled and run without problems. So are they equivalent?

Thank.

+5
source share
1 answer

There is a difference if you want to create a pointer type alias.

typedef int *t1;
#define t2 int *

t1 a, b; /* a is 'int*' and b is 'int*' */
t2 c, d; /* c is 'int*' and d is 'int'  */

In addition, it typedefobeys the scope rules, i.e. you can declare a type as a local block.

On the other hand, you can use #defineit when you want to control the type in the preprocessor directive.

+20
source

All Articles