6

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 compile and run without problems. So, are they equivalent?

Thanks.

Community
  • 1
  • 1
user1274605
  • 405
  • 2
  • 6
  • 17

1 Answers1

23

There is a difference when you want to create an alias of a pointer type.

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'  */

Moreover, typedef obeys scope rules, i.e. you can declare a type local to a block.

On the other hand, you can use #define when you want to manage your type in a preprocessor directive.

Community
  • 1
  • 1
md5
  • 23,373
  • 3
  • 44
  • 93