Explanation of C language typedef
In C or C ++ Code, many types of typedef are used. Typedef is similar to # define, which is actually different.
Basic definition: typedef is a keyword of C language. It defines a new name for a data type. The data types here include basic data types (int, char ), it also includes Custom Data Types (struct ).
(1) differences with # define
Typedef is a bit like # define macro, and its actual type replaces the synonym. The difference is that typedef is interpreted during compilation, so let the compiler handle text replacement beyond the pre-processor capability.
(2) reduce errors
Define a type of Alias, not just a simple macro replacement. It can be used as multiple objects that declare the pointer type at the same time. For example:
char* pa,pb;
Most of these do not conform to our intention. It only declares a pointer to a character variable and a character variable. You can modify it as follows:
typedef char* pchar;pchar pa,pb;
This method is very useful, especially the definition of char * pa and pb;. Beginners often think that two character pointers are defined, but not actually, this problem will not occur if typedef char * pchar is used, reduces errors.
(3) intuitive and concise
It is used in the old C code and in combination with struct. In the previous Code, when declaring a new struct object, it must contain struct, that is, the object name in the form of struct name. For example:
struct tagPOINT1 { int x; int y;};struct tagPOINT1 p1;
If typedef code is used:
Typedef struct tagPOINT {int x; int y;} POINT; POINT p1; // You Can Do This; struct tagPOINT p2; // You can also do this;
Or:
typedef struct { int x; int y;}POINT;POINT p1;
POINT p1; in this way, it is easier to write less struct than the original method, especially when it is used in large quantities.
(4) platform independence
Use typedef to define platform-independent types. For example, you can define a REAL floating point type and obtain the highest precision on the target machine.
typedef long double REAL;
On a machine that does not support long double, you can change it to the following:
typedef double REAL;
If the double type is not supported, change it to the following:
typedef float REAL;
That is to say, when using a cross-platform system, you only need to change the typedef itself, without any modifications to other source codes.