When I was learning data structure again, I found that I had forgotten a lot of the knowledge I had learned before. After discovering that my understanding of the keyword typedef in C/C++ was still not in place, I read through the textbooks used to learn C++. I asked Du Niang again and read a lot of blogs about the usage of typedef. So I wanted to sort out what I understood.
1. Basic explanation
Typedef is a keyword in C language, which is used to define a new name for a data type. The data types here include internal data types (int, char, etc.) and custom data types (struct, etc.).
There are generally two purposes of using typedef in programming. One is to give variables a new name that is easy to remember and has clear meaning. The other is to simplify some more complex type declarations.
2. Usage
(1) Use typedef to declare a new type name to replace the existing type name. For example:
typedef int Status //指定标识符Status代表int类型 typedef double DATE //指定标识符DATE代表double类型
The following code is equivalent to:
int i; double j; Status i;DATE j;
(2) Use typedef to give a new name to the array type:
typedef int NUM[100];//声明NUM为整数数组类型,可以包含100个元素 NUM n;//定义n为包含100个整数元素的数组,n就是数组名
(3) Declare a new name for a structure type:
typedef struct //在struct之前用了关键字typedef,表示是声明新类型名 { int month; int day; int year; } TIME; //TIME是新类型名,但不是新类型,也不是结构体变量名
Newly declared new type The name TIME represents a structure type specified above, so you can use TIME to define the structure variable, such as:
TIME birthday; TIME *P //p是指向该结构体类型数据的指针
Three. Note: (1) Using typedef only adds a type name to an existing type, but does not create a new type. It just adds a new name, and you can use this name to define variables. For example, use the Status above to define variable i; then the type of i variable is int.
(2) You can use typedef to declare a new type name. But it cannot be used to define variables
4. Advantages
Using typedef type names is beneficial to program portability. Sometimes programs rely on hardware features. For example, in a certain C++ system, 2 bytes are used to store an int type variable, and 4 bytes are used to store a long type variable. In another C++ system, int type variables are stored in 4 bytes. When transplanting a C++ program from a C++ system that uses 2 bytes to store an int type variable to a C++ system that uses 4 bytes to store an int type variable, if the original typedef is used to declare the int type, for example:
Typedef int INTEGER ; //原来这样写 Typedef long INTEGER ; //移植后可以改为这样
If it is not declared with typedef, then every place where the int type is defined must be changed. The larger the program, the greater the workload.