typedef and # define are often used to define an alias for an identifier and a keyword, but there are key differences between them.
typedef is part of the language compilation process;
#define是宏定义语句, it is not in the process of compiling itself, but before the preprocessing process is done.
To understand the key differences between the two, you can consider this:
Seeing a typedef as a complete "encapsulation" type is equivalent to creating a new variable type (which is similar to a struct and will be likened to a struct to enhance understanding). and # define is just a macro text substitution.
The differences between typedef and #define are reflected in two areas:
First, the macro type name can be extended with other type specifiers, but the type name defined by the typedef cannot be extended.
As follows:
#define PEACH INT
unsigned peach i; No problem, you can use it this way.
typedef int Banana;
unsigned banana i; Wrong, illegal!
#define is just a macro text substitution, it does not produce a new variable type. Taking the above code as an example, in the preprocessing phase, peach is replaced with int, so it can be added unsigned in front of peach;
The typedef works in a different way than the # define, which is equivalent to creating a new variable type that cannot be extended before the new variable type. This is similar to struct type, where a struct is defined to produce a new variable type, and we never see a unsigned struct student A; Such a declaration.
The second difference, in declarations of successive variables, is that a type defined with a typedef guarantees that all variables in the declaration are of the same type, and that a # define is not guaranteed.
As follows:
#define INTP int *
INTP A, B;
After macro expansion, the second line becomes:
int * A, B;
A is a pointer variable to an int variable, and b is a variable of type int!typedef int * int_p;int_p C, D; C, d are pointer variables that point to int variables!
In the above code example, #define仅仅是进行宏替换, in the preprocessing phase INTP is replaced with an int *, which obviously can only declare that a is a pointer variable, and b is an int variable. A typedef is the equivalent of defining a new variable type that can work on both C and D. Similarly with struct analogy, for struct student e,f; Both E and F are declared to be variables of type student.