Typedef is used to define type analysis

  • 2020-04-02 01:26:42
  • OfStack

Such as:
Typedef int INTEGER;
Typedef float REAL;

Specify INTEGER for int and REAL for float, so that the following two lines are equivalent:
1) int I, j;   Float a, b;
2) INTEGER I, j;     REAL a, b;

Structure type can be declared:


typedef struct
{
int month;
int day;
int year;
}DATE;

When you declare a new type, DATE, you can use DATE to define a variable: DATE birthday (don't write struct DATE birthday;) ; The DATE * p; // pointer to a struct type.

Further:
1) typedef int NUM[10]; // declares an integer array type
      NUM n; // define n as an integer array variable, where n[0]--n[9] is available

2) typedeff char* STRING; // declares STRING as character pointer type
      A STRING of p, s [10]; //p is the character pointer variable, s is the pointer array

3) typedeff int (*POINTER)(); // declares POINTER as a POINTER to a function that returns an integer value with no arguments
      POINTER (P1, P2, //p1, p2 are POINTER variables of type POINTER

Description:
1) type defs can be used to declare various type names, but not to define variables. Type defs can be used to declare array types and string types, which is convenient to use.

For example: define an array with: int a[10],b[10],c[10],d[10]; Since both are one-dimensional arrays with the same size, you can first declare the array type as a name:
Typedef int ARR [10].

Then use ARR to define array variables:
ARR a, b, c, d; //ARR is an array type that contains 10 elements. So a,b,c, and d are all defined as one-dimensional arrays with 10 elements. As you can see, an array type can be separated from an array variable with a typedef, and an array type can be used to define multiple array variables. You can also define string types, pointer types, and so on.

2) the use of typedefs merely adds a type name to an existing type without creating a new type.

3) typedef is similar to #define, but in fact they are different. #define is handled at precompile time, which can only do simple string substitution, while typedef is handled at compile time. Instead of doing a simple string substitution, it declares a type as if it were a variable.

For example: typedef int COUNT; And #define COUNT int both use COUNT for int, but they're actually different.

4) when the same type of data is used in different source files, it is often used to declare some data types with typedefs, put them in a single file, and then include them with the #include command in the files that need to use them.

5) typedef is conducive to the general use and transplantation of procedures.


Related articles: