C Language Notes: Defining Types with typedef

In the C language, you can use typedef to define an alias for existing types (including int, double, long, structures, etc.). The alias can be used to define variables just like standard type names.

01

Usage Form

The usage form of typedef is as follows:typedef standard type name alias;For example:

typedef int IN;

After this, defining an integer variable can be done with the following two lines of code, which are equivalent:

int a;IN b;

The int type itself is quite simple, and in practical programming, it is not common to perform such operations on the int type. However, using typedef to define an alias for more complex types like structures can make programming more convenient. For example:

typedef struct student{    int no;    struct student * next;}STU;

After this, when defining a variable of the student structure type or a pointer to the student structure type, you can directly use STU, which clearly shows its advantages:

STU a;// Defines a variable a of student structure typeSTU * h;// Defines a pointer variable h pointing to student structure type

02

Comparison of typedef and #define

typedef and #define have similarities in that both replace synonyms with actual types. However, they are actually different; the distinction is that typedef is executed by the compiler at compile time, while define is processed by the preprocessor during compilation preprocessing and can only perform simple string replacements.

03

Some Notes

Using typedef only adds an alias to an existing type; it does not create a new type. Just like a person, besides their given name, they can also have a nickname, pen name, stage name, etc. Regardless of which name is used, the person remains the same and does not create another person.typedef can also be used in defining pointers:

int *n1,n2;

The programmer intended to define two int-type pointer variables, but what is actually defined is that n1 is a pointer variable, while n2 is a regular integer variable. You can use typedef to define integer pointers:

typedef int * POINT;POINT n1,n2;

This definition method is even more advantageous when a large number of pointers need to be defined.

Leave a Comment