typedef Vs. #define

In this post I’ll try to summarize several posts I’ve read talking about differences between them


  • Handled by the compiler itself.
  • An actual definition of a new type (some people said adding new alias).
  • typedef obeys scoping rules just like variables.
  • The type defined with a typedef is exactly like its counterpart as far as its type declaring power is concerned BUT it cannot be modified like its counterpart. For example, let’s say you define a synonim for the int type with:
typedef int MYINT
//Now you can declare an int variable either with
int a;
//But you cannot declare an unsigned int (using the unsigned modifier) with
unsigned MYINT a;
unsigned int a;
//would be perfectly acceptable.
  • typedefs can correctly encode pointer types.
  • Some things can be done with typedef that cannot be done with define. Examples:
typedef int* int_p1;
int_p1 a, b, c;  // a, b, and c are all int pointers.

#define int_p2 int*
int_p2 a, b, c;  // only the first is a pointer!
typedef int a10[10];
a10 a, b, c; // create three 10-int arrays
typedef int (*func_p) (int);
func_p fp // func_p is a pointer to a function that
          // takes an int and returns an int


  • Handled by the preprocessor (a program run before actual compiler).
  • Works like replacing all in your editor.
  • #DEFINES are just replacements done by the preprocessor. For example:
  1. typedef char *String_t;
  2. #define String_d char *
  3. String_t s1, s2; String_d s3, s4;

s1, s2, and s3 are all declared as char *, but s4 is declared as a char, which is probably not the intention.

  • #define stays valid until the end of the file (or until a matching undef).
  • A #define is just a macro, i.e. it will be processed/expanded by the preprocessor.

2 thoughts on “typedef Vs. #define

  1. فل يا ريس :D:D

    بس ليه بقى هنا
    #define int_p2 int*
    int_p2 a, b, c;

    بيحصل كده
    // only the first is a pointer! ؟؟

    والباقيين بيبقوا ايه لو هما مش بوينترز ؟

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s