Wednesday, March 27, 2013

typedef and #define

While browsing I found someone asking “difference between typedef and #define”. I thought a moment, why the person is asking difference between two different entities altogether.  Typedef is used to give different names to existing data types [int, char, float etc]. Whereas #define is a preprocessor directive which replaces identifier with token.
Look at below c programs.
Program 1
#include <stdio.h>
 
#define type int
 
type main()
{
        type count=10;
        printf("count = %d",count);
        return 0;
}
 
Program 2
#include <stdio.h>
 
typedef int type;
 
type main()
{
        type count=10;
        printf("count = %d",count);
        return 0;
}
 
In the above two programs does typedef and #define behave differently?
 
Both are replacing word "type" with “int”.Finally the end result is same. But the replacement process happens in different phases. #define replaces word "type" with ” int” in preprocessing stage, typedef replaces word "type" with “int” in compilation stage.
 
I was trying below programs while thinking of difference between typedef and #define.
 
Program 1
 
#include <stdio.h>
typedef int int
 
int main()
{
        int count=10;
        printf("count = %d",count);
        return 0;
}
 
If you compile this program it ends up in error.
error: two or more data types in declaration specifiers
error: two or more data types in declaration specifiers
error: function definition declared typedef
 
Program 2
 
#include <stdio.h>
 
#define int int
 
int main()
{
        int count=10;
        printf("count = %d",count);
        return 0;
}
 
If you compile this program, it compiles successfully and displays correct output. So we can add this difference too.

No comments:

Post a Comment