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
//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; 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:
- typedef char *String_t;
- #define String_d char *
- 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.