typedef and #define are commonly used in C\C++. Below are some of the difference and similarity between them

  • typedef is used to give data type a new name. #define is a C\C++ directive which is used to define alias.
// BYTE can be used in place of unsifned char
typedef unsigned char BYTE;

// HYD is replaced by "Hyderabad"
define HYD "Hyderabad"
  • typedef interpretation is performed by the compiler where #define statements are performed by preprocessor.
  • define should not be terminated with semicolon, but typedef should be terminated with semicolon.
  • typedef follows the scope rule which means 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. In case of #define, when preprocessor encounters #define, it replaces all the occurrences, after that (No scope rule is followed).
  • Some things can be done with typedef that cannot be done with define.
// a, b, c are all int pointers
typedef int* int_p1;
int_p1 a, b, c;  

// only the first is a pointer, because int_p2 is replaced with int*, 
// producing: int* a, b, c which should be read as: int *a, b, c
#define int_p2 int*
int_p2 a, b, c;