C language Define and TypeDef, both have similarities, but also different points.
Here is a similarity between the two:
The C language allows typedef to define a new name for various data types, and the TypeDef declaration is basically the same as the normal declaration, except that the typedef appears in front of the declaration.
For example: typedef char *PTR;
This declaration uses the identifier PTR as a new name for the pointer type pointing to the character pointer, which can be used in the following declaration, as with any predefined name.
For example: ptr A; (Declaring A is a pointer to a character)
For macro define:
Example: #define PTR char *
PTR A;
This PTR, defined by define, is replaced with a char * type, which makes a a pointer to a character type, which is the same as the effect of the preceding typedef.
Here are the specific differences:
1) #define是预处理指令, in the compilation of pre-processing only simple substitution, not for correctness check, whether the meaning is correct only replace, only the execution of the program will find errors and error.
Example: #define PI 3.1415926
In the program: Area=pi*r*r is replaced with 3.1415926*r*r, if the number 9 in the # define statement is written as the letter G preprocessing is also brought in.
2) A typedef is processed at compile time, giving an alias to an already existing type within its own scope.
3) typedef int *INT_PTR; with #define INT_PTR int*
The function is to use INT_PTR to represent the int*, but the two are different, as previously said, #define在预处理时进行简单的替换, and typedef is not a simple substitution, but rather a way of declaring a type as a method of defining a variable.
4) #define不是语句, do not add semicolons at the end of the line, or they will be replaced with a semicolon.
This article from "Unintentional persistent" blog, reproduced please contact the author!
Define and typedef differences