Difference between typedef and #defineDifference between #define and typedef

The #define is a C-directive which is also used to define the aliases for various data types similar to typedef but with following differences:

  • The typedef is limited to giving symbolic names to types only where as #define can be used to define alias for values as well, like you can define 1 as ONE etc.


  • The typedef interpretation is performed by the compiler where as #define statements are processed by the pre-processor.


  • #define should not be terminated with semicolon, but typedef should be terminated with semicolon.




  • #define will just copy-paste the definition values at the point of use, while typedef is actual definition of a new type




  • typedef follows the scope rule which mean if a new type is defined in a scope(inside a function), then the new type name will only be visible till the scope is there.
                                  But in preprocessor case, when preprocessor encounters a #define, then it will replace all the occurrences, after that (No scope rule is followed). See below example:




  • There are certain types of definitions which you can only define using typedef only and not #define like below



  • There is some benefit of typedef when we define structure with typedef like this




Problems on typedef and #define

This problems will clear some doubts and give you practical idea

1. What is the output of this C code?


a) Compile time error
b) Varies
c) he
d) hey


2. What is the output of this C code?


a) Compile time error
b) 1
c) 0
d) Depends on the standard


3. The correct syntax to use typedef for struct is.


4. typedef int (*PFI)(char *, char *)creates
a) type PFI, for pointer to function (of two char * arguments) returning int
b) Error
c) type PFI, function (of two char * arguments) returning int
d) type PFI, for pointer


5. For the following expression to work, which option should be selected.
    string p = “HELLO”;
a) typedef char [] string;
b) typedef char *string;
c) Both (a) and (b)
d) Such expression cannot be generated in C 


6. What is the output of this C code?


a) Compiler error
b) 8,8,8,8
c) 1,1,1,1
d) 8,8,8,1

 Answers: (1: d) , (2: a) , (3: d) ,(4: a ) , (5: b), (6: d)