Typedef declaration, or typedef for short, creates a new name for an existing type. For example, typedef is often used to write more beautiful and readable code. The so-called beauty means that typedef can hide clumsy Syntax structures and platform-related data types to enhance portability and future maintainability.
Typedef is used most often to create a type name that is easy to remember and use it to archive the programmer's intent. Type appears in the declared variable name, which is on the right of the ''typedef ''keyword. For example:
Typedef int size;
This statement defines an int synonym with the name size. Note that typedef does not create a new type. It only adds a synonym for an existing type. You can use size in any context that requires an int.
Typedef can also conceal composite types, such as pointers and arrays. For example, you do not need to repeatedly define an array with 81 characters as follows:
Char line [81];
Char text [81];
Define a typedef. Whenever an array of the same type and size is used, you can do this:
Typedef char line [81];
Line Text, secondline;
Another important purpose of typedef is to define machine-independent types. For example, you can define a floating point type called real. On the target machine, it can obtain the highest precision:
Typedef long double real;
On a machine that does not support long double, the typedef looks like the following:
Typedef double real;
In addition, on a machine that does not support double, the typedef looks like this:
Typedef float real;
You do not need to make any changes to the source code, you can compile this real-type application on each platform. The only change is typedef itself. In most cases, even this tiny change can be automatically implemented through fantastic Conditional compilation. Isn't it? The standard library uses typedef to create such platform-independent types: size_t, ptrdiff, and fpos_t. In addition, typedef such as STD: string and STD: ofstream also hides long, incomprehensible template-specific syntax, such as: basic_string <char, char_traits <char>, allocator <char> and basic_ofstream <char, char_traits <char>.
Note 1: note the difference between typedef and define.
Typedef KKK int *
Kkk a, B
Then A and B are of the same type.
Define KKK int *
Kkk a, B
The A and B types are different.
NOTE 2:
Typedef int (* mac_listen_func) (int *, char *);
Mac_listen_func mlf1, mlf2;
Equivalent Definition:
INT (* mlf1) (int *, char *);
INT (* mlf1) (int *, char *);
The above method is easy to use and easier to read.