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.
typedef is limited to giving symbolic names to types only, whereas #define can be used to define an alias for values as well, e.g., you can define 1 as ONE, 3.14 as PI, etc. typedef interpretation is performed by the compiler where #define statements are performed by preprocessor.
Basically struct is used to define a structure. But when we want to use it we have to use the struct keyword in C. If we use the typedef keyword, then a new name, we can use the struct by that name, without writing the struct keyword.
The typedef has the advantage that it obeys the scope rules. That means you can use the same name for the different types in different scopes. It can have file scope or block scope in which declare. In other words, #define does not follow the scope rule.
typedef is a reserved keyword in the programming languages C and C++. It is used to create an additional name (alias) for another data type, but does not create a new type, except in the obscure case of a qualified typedef of an array type where the typedef qualifiers are transferred to the array element type.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With