To put it simply, # define is simply replaced, while typedef gets an "alias" for the type ".
1. # define is a pre-processing command. It is a simple replacement during compilation and pre-processing. It does not check the correctness or whether the meaning is correct, possible errors are detected and reported only when the expanded source program is compiled. For example:
#define PI 3.1415926
In the program, area = PI * r is replaced with 3.1415926 * r.
If you write the number 9 in the # define statement as a letter g, the preprocessing will also be carried in.
2. typedef is processed during compilation. It gives an existing type an alias in its own scope, but You cannot use the typedef specifier inside a function definition.
3. typedef int * int_ptr; and # define int_ptr int * both use int_ptr to represent int *, but they are different. As mentioned above, # define is replaced simply during preprocessing, typedef is not a simple replacement, but a type is declared as if it were a variable. That is to say:
// Refer to (xzgyb (Lao Damo) # define int_ptr int * int_ptr a, B; // equivalent to int * a, B; just replace typedef int * int_ptr with a simple macro; int_ptr a, B; // a and B all point to the int pointer. If typedef is int *, a new mnemonic is introduced.
Pointer difference:
#include <iostream>#include <typeinfo>using namespace std;int main(){ typedef char * CHAR; CHAR c,d; cout << typeid(c).name() << endl << typeid(d).name() << endl;#define CH char* CH c1,c2; cout << typeid(c1).name() << endl << typeid(c2).name() << endl; return 0;}
This also explains why the following points are true:
typedef int * pint ;#define PINT int *
So:
Const pint p; // p cannot be changed, but the content that p points to can be changed const PINT p; // p can be changed, but the content that p points cannot be changed.
Pint is a pointer type. const pint p is used to lock the pointer. p cannot be changed. Const PINT p is the object indicated by pointer p.
3. You may have noticed that # define is not a statement. Do not add points at the end of the line. Otherwise, a semicolon is replaced.