C language typedef keyword

Source: Internet
Author: User
C language typedef keyword

Joke about the vest. There was a joke: A hunter caught a snake by the river and the snake escaped into the water. After a while, a tortoise climbs to the shore. The Hunter grabbed the turtle and said loudly: Look, don't you wear a vest for you. I don't know you!
The typedef keyword is a great sewing artist who is good at creating a vest. When you put on this vest, it immediately changes. It can turn a wolf into a sheep or a wolf. You can even turn a bird with wings into an angel, or a beautiful angel into a bird. Therefore, you must never offend it. You must master its temper. Otherwise, I will treat you as a bird someday, so don't blame me. O (distinct _ distinct) O ~

I. Misunderstanding of history-it may be typerename.

Many people think that typedef is to define a new data type, which may be related to this keyword. Originally, type is the meaning of the Data Type; def (INE) is the meaning of the definition. In combination, it is the definition of the data type. Unfortunately, this understanding is incorrect. Maybe this keyword should be replaced with "typerename" or another word.
Typedef really means to get an alias for an existing data type (Note: it is a type rather than a variable), rather than defining a new data type.For example, the magnificent peony has an alias-"leaving ". In ancient China, the relationship between men and women often presented to them with "Yao" to express their feelings of farewell. "Yao" is about to be separated. Therefore, the literati gave Yao a meaningful alias-"leaving ". This new name expresses the reluctance to say goodbye... In this way, the new name is more expressive than the original name.

In actual projects, for convenience, many data types (especially custom data types such as struct) need to be retrieved from a new alias that applies to the actual situation. In this case, typedef can help us. For example:

Typedef struct student
{
// Code
} Stu_st, * stu_pst;
A) There is no difference between struct student stu1 and stu_st stu1.
B) struct student * stu2; there is no difference between stu_pst stu2 and stu_st * stu2.


Why are the two definitions of B equal? In fact, it is easy to understand. We regard "struct student {/* Code */}" as a whole, and typedef is to give "struct student {/* Code */}" the name of a few "stu_st "; in addition, "struct student {/* Code */} *" is assigned the name of "stu_pst ". These two names are all the same. For example, if you give your puppy some names "rhubarb" and your sister brings a small hat to the puppy, then I gave it some names: "cute ". ^_^.

Whether in C or C ++ code, the word typedef is widely used. Of course, the frequent occurrence is still in C code. Typedef is similar to # define, but it is more different, especially in some complicated usage, I read some blogs of C/C ++ learners on the Internet. One of the blogs about typedef is still very good. Because of the excellent summary, I will not add any modified references.

Purpose 1:

Define a type of Alias, not just a simple macro replacement. It can be used as multiple objects that declare the pointer type at the same time. For example:

Char * pA, PB; // most of them do not conform to our intention. It only declares a pointer to a character variable and a character variable;
The following are feasible:
Typedef char * pchar;
Pchar Pa, PB;


This usage is very useful, especially the definition of char * pa and Pb. Beginners often think that two character-type pointers are defined. Actually, this is not the case. Using typedef char * pchar won't happen, reduces errors.

Purpose 2:

It is used in the old C code to help struct. In the previous Code, when declaring a new struct object, you must carry the struct, that is, the form is: struct structure name object name, such:

Struct tagpoint1

{


Int X;


Int y;

};

Struct tagpoint1 P1;

In C ++, you can directly write: Structure name object name, that is, tagpoint1 P1;

Typedef struct tagpoint
{
Int X;
Int y;
} Point;

Point P1;

In this way, it is easier to write a struct less than the original method, especially when it is used in large quantities. Maybe, in C ++, typedef is not very useful in this way, however, understanding it is helpful to grasp the Old Code. After all, we may encounter code left over from earlier years in the project.

Purpose 3:

Use typedef to define platform-independent types.

For example, define a floating point type called real. On the target platform 1, make it the highest precision type:
Typedef long double real;
On Platform 2 that does not support long double, change:
Typedef double real;
On Platform 3 that is not supported by double, change:
Typedef float real;
That is to say, when using a cross-platform system, you only need to change the typedef itself, without any modifications to other source codes.


This technique is widely used in the standard library, such as size_t. In addition, because typedef defines a new type of Alias, rather than a simple string replacement, it is more robust than a macro.

This advantage can reduce the amount of Code while writing code!

Purpose 4:

Define a new simple alias for complex statements. The method is: gradually replace a part of the complex declaration with an alias in the original declaration. In this loop, leave the part with the variable name to the final replacement, and the most simplified version of the original declaration is obtained. Example:

Original Declaration: void (* B [10]) (void (*)());

The variable name is B. Replace pfunparam with alias 1 in the brackets on the right:

Typedef void (* pfunparam )();

Replace B with the variable on the left, and pfunx with alias 2:

Typedef void (* pfunx) (pfunparam );

The most simplified version of the original statement:

Pfunx B [10];

Original statement: Doube (*) (* E) [9];

The variable name is E. Replace the left part with pfuny as Alias 1:

Typedef double (* pfuny )();

Replace the variable E on the right, and pfunparamy is alias 2.

Typedef pfuny (* pfunparamy) [9];

The most simplified version of the original statement:

Pfunparamy E;

Understand the "right-left rule" available for complex statements: Starting from the variable name, you must first go to the right and then to the left. When you encounter a parentheses, you can adjust the reading direction. After analyzing the parentheses, you can jump out of the brackets, it is still in the order of the first right and then the left, until the entire declaration analysis is complete. Example:

INT (* func) (int * P );

First, find the variable name func, and there is a pair of parentheses on the outside, and there is a * sign on the left, which indicates that func is a pointer. Then jump out of the parentheses and look at the right first, this indicates that (* func) is a function, so func is a pointer to this type of function, that is, a function pointer. This type of function has an int * type parameter, and the return value type is int.

INT (* func [5]) (int *);

The right side of func is a [] Operator, indicating that func is an array with five elements; there is a * on the left of func, indicating that the func element is a pointer (note that * is not a modifier of func, instead, modify func [5] Because the [] operator has a higher priority than *, and func is first combined ). Jump out of the brackets and look at the right side. The parentheses indicate that the element of the func array is a pointer of the function type. It points to an int * type parameter and the return value type is int.

This kind of usage is complicated, and there are many occurrences of this kind of usage, which is often not understandable. I believe the above explanation can be helpful.

The following is an example. If it is used in the future, it will earn O (cost _ cost) O ~

 

# Include <stdio. h> typedef int (* fp_calc) (INT, INT); int add (int A, int B) {return a + B;} int sub (int A, int B) {return a-B;} int MUL (int A, int B) {return a * B;} int Div (int A, int B) {return B? A/B:-1;} fp_calc calc_func (char OP) {Switch (OP) {Case '+': Return add; // return function address case '-': return sub; Case '*': Return Mul; Case '/': Return div; default: return NULL;} int (* s_calc_func (char OP )) (INT, INT) {return calc_func (OP);} int calc (int A, int B, char OP) {fp_calc fp = calc_func (OP ); // obtain the address of various arithmetic functions based on the budget operator // You can also use the following method // int (* s_fp) (INT, INT) = s_calc_func (OP ); // used for testing // assert (FP = s_fp); // You can assert that the two are equal if (FP) return FP (A, B ); else return-1;} void main () {int A = 100, B = 20; printf ("calc (% d, % d, % C) = % d \ n ", a, B, '+', Calc (a, B, '+'); printf (" calc (% d, % d, % C) = % d \ n ", a, B, '-', Calc (a, B, '-'); printf (" calc (% d, % d, % C) = % d \ n ", a, B, '*', Calc (a, B ,'*')); printf ("calc (% d, % d, % C) = % d \ n", a, B, '/', Calc (A, B, '/'));}

Result

 

 

calc(100, 20, +) = 120calc(100, 20, -) = 80calc(100, 20, *) = 2000calc(100, 20, /) = 5

If you want to know more, you can look at this code, which is much easier to understand.

 

To be continued ......

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.