Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between typedef and define [duplicate]

Tags:

c

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.

like image 487
user1274605 Avatar asked Aug 30 '12 17:08

user1274605


People also ask

What is the difference between typedef and define?

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.

What is the difference between typedef and structure?

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.

Why typedef better than definition?

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.

What does typedef mean?

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.


1 Answers

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.

like image 72
md5 Avatar answered Nov 06 '22 09:11

md5