Friday, March 18, 2011

difference between typedef and #define

lets have a look at whats the difference between typedef and #define.....

A typedef is just a new name for an already existing type and defines are handled by the preprocessor while typedefs are handled by the C compiler itself.
#define can be used to rename anything not just a type like typedef.................for e.g.

#define AND && and we cant use typedef for that like typedef && AND; its not possible with typedef...... some more examples like #define PRINT printf("hello") or #define sum(a,b) (a+b)....all this is not possible with typedef...................

we all know this very well so i am not going to explain this but what will happen if we use #define to rename a type................

suppose if we have
typedef char * ptr;
#define PTR char *

both of them are looking similar......


lets understand the difference with the help of an example............

typedef char * ptr;
#define PTR char *
int main()
{
ptr a,b,c;
PTR x,y,z;
printf( "sizeof a:%u\n" ,sizeof(a) );
printf( "sizeof b:%u\n" ,sizeof(b) );
printf( "sizeof c:%u\n" ,sizeof(c) );
printf( "sizeof x:%u\n" ,sizeof(x) );
printf( "sizeof y:%u\n" ,sizeof(y) );
printf( "sizeof z:%u\n" ,sizeof(z) );
return 0;
}

Output:
sizeof a:2
sizeof b:2
sizeof c:2
sizeof x:2
sizeof y:1
sizeof z:1

Explanation:
in case of turbo C compiler the size of pointer is 2 and in other compilers it is different it may be 4 like in dev compiler .........thats not our point of discussion.....we have to discuss why is there such output.........

Note that y and z do not have the same size as the x whereas a,b and c are consistent. Why is this? Simple: we used a macro for x y and z.

Look at what the macro actually does:

#define PTR char *

PTR x,y, z;
This is in turn converted (by simple text substitution) to:
char *x ,y, z;
That line does not define three pointer variables. It defines three variables with a base type of "char" one of which x is a pointer. It is the same as writing:
char *x;
char y;
char z;
The typedef dont fail this way because when we defined the new type we defined it specifically as a pointer type meaning that any variable defined with the new type will in fact be a pointer variable.......

No comments:

Post a Comment

Feel free to comment......