1. Difference
(1) Definition, execution time, scope
Definition, Execution time:
#define pchar char *
typedef char *pchar;
The definition of the format difference, it is obvious to note that define is not a semicolon (text substitution), and typedef is a comma (type of renaming).
At the same time, the define is processed by the preprocessor, making simple text replacement work without any checks (correctness check, scope check, type check)
A typedef is an alias for an already existing type, which is processed at compile time.
Scope:
Define once defined, there is no scope limit, where it can be used:
void func1()
{
#define HW "HelloWorld";
}
void func2()
{
string str = HW;
cout << str << endl;
}
typedef is not, there is its own scope.
void func1()
{
typedef unsigned int UINT;
}
void func2()
{
UINT uValue = 5;//error C2065: ‘UINT‘ : undeclared identifier
}
(2) operation of the pointer
#define pint int*
typedef int* ppint;
pint a1, b1;
ppint c1, d1;
The above definition is equivalent to
int * a1;
int b1;
int * c1;
int * d1;
For the way in which pointers are defined, use typedef to be reliable.
2, the combination of typedef and const
When:
typedef int * pint;
int a = 1;
const pint p1 = &a;
*p1 = 2;
cout << *p1 << endl;
The result was printed: 2
Visible: Const pint P1, is equivalent to the int * Const P1, that is, p1 is a const pointer, P1 point to the address is a constant (cannot change), so the definition of the time needs to be initialized, but P1 know the content can be modified, change to 2 printout.
Visible, even in the order of change, is equivalent to: int * const P1; That is, no matter how the order is picked, it is a defined const pointer.
Typedef int * pint;
Int a = 1;
Pint const p1 = &a;
*p1 = 2;
Cout << *p1 << endl;
Print: 2
If you do not want to define a const int * Type, you can only:
typedef const INT * CPINT;
Only this method is defined to define a pointer to a const.
3. TypeDef effect
(1) simplify Complex type description
Int(*pfunc)(int,int)
Use typedef:
Typedef int(*pfunc)(int,int)
Use:
Pfunc ptr = function name;
(2) Define platform-independent types
The definition of a data type is generally related to the platform. For large code, if the definition is: long double A; But when the platform does not support long long type, to enter the code body one by one, it is really deadly:
Long Double REAL;
In the cross-platform, only need to modify it all resolved.
4, the package degree is different
typedef and define are not the same in the seam of UN degree. typedef can be seen as a complete "encapsulation" type, meaning that after a typedef is declared, it is no longer possible to add anything else to it. And define is not, he is only a text replacement work, so after the declaration can be encapsulated.
#define zhengxing1 int
unsigned zhengxing1 i;
The compiler passed correctly.
typedef int zhengxing2;
unsigned zhengxing2 j;
The compiler is not compiled.
The difference between typedef and define