Typedef is a key word in C language. It defines a new name for a data type. The data types here include internal data types (int, char, etc.) and Custom Data Types (struct, etc ).
In programming, typedef is generally used for two purposes. One is to give a variable a new name that is easy to remember and clear, and the other is to simplify some complicated type declarations.
As for the nuances of typedef, let's take a look at the specifics of several problems.
I
First, define a struct type in C to use typedef:
typedef struct Student{int a;}Stu;
So when declaring the variable, you can: Stu stu1;
If there is no typedef, it must be declared using struct Student stu1.
The Stu here is actually the alias of struct Student.
In addition, Student can also be left empty (so it cannot be struct Student stu1 ).
typedef struct{int a;}Stu;
However, in c ++
struct Student{int a;};
So Student is defined, and Student stu2 is directly used when variables are declared.
II
Second, if typedef is used in C ++, the difference may occur:
Struct Student {int a;} stu1; // stu1 is a variable typedef struct Student2 {int a;} stu2; // stu2 is a struct type
You can directly access stu1.a during use, but stu2 must first stu2 s2; and then s2.a = 10;
3.
You can master the above two items, but at last we will discuss some issues that do not matter much.
If we write:
typedef struct {int num;int age;}aaa,bbb,ccc;
What is this?
I personally observe the understanding of the compiler (VC6), which is equivalent
typedef struct {int num;int age;}aaa;typedef aaa bbb;typedef aaa ccc;
That is to say, aaa, bbb, and ccc are all struct types. When declaring a variable, you can use any one. This is also true in c ++. However, note that if the typedef keyword is written in c ++, aaa, bbb, and ccc will be completely different objects.