Definition and usage of typedef in C/C ++

Source: Internet
Author: User

In C or C ++ Code, many types of typedef are used, especially in C code. Typedef is somewhat similar to # define, but it is actually different. Especially in some complicated usage, I read the blog of some C/C ++ learners on the Internet, one of the articles about typedef is still very good. As the summary is very good, I will not add the modified references and add my own analysis.

Basic Definition:
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.

Purpose 1: Differences with # define
Typedef acts a bit like # define macro and replaces the synonym with its actual type. The difference is that typedef is interpreted during compilation, so let the compiler handle text replacement beyond the pre-processor capability.

Purpose 2: reduce errors
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:Copy codeThe Code is as follows: 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:Copy codeThe Code is as follows: 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 3: intuitive and concise
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:Copy codeThe Code is as follows: struct tagPOINT1
{
Int x;
Int y;
};
Struct tagPOINT1 p1;

In C ++, you can directly write: Structure name object name, that is, tagPOINT1 p1;Copy codeThe Code is as follows: typedef struct tagPOINT
{
Int x;
Int y;
} POINT;

POINT p1; // in this way, a struct is written less than the original method, which is easier to use, especially in the case of a large number of usage. Maybe, in C ++, typedef is not very useful, but it is helpful to understand the old code, after all, we may encounter code that was left behind in earlier years in the project.

Purpose 4: platform independence
Use typedef to define platform-independent types.
Another important purpose of typedef is to define machine-independent types. For example, you can define a REAL floating point type, which can achieve the highest precision on the target machine:Copy codeThe Code is as follows: typedef long double REAL;

On a machine that does not support long double, the typedef looks like the following:Copy codeThe Code is as follows: typedef double REAL;

In addition, on a machine that does not support double, the typedef looks like this:Copy codeThe Code is as follows: 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.

Purpose 5: Hide composite types
Typedef can also conceal composite types, such as pointers and arrays.
For example, you do not need to repeatedly define an array with 81 characters as follows:Copy codeThe Code is as follows: char line [81];
Char text [81];

Define a typedef. Whenever an array of the same type and size is used, you can do this:Copy codeThe Code is as follows: typedef char Line [81];

In this case, the Line type represents a string array with 81 elements. The usage is as follows:Copy codeThe Code is as follows: Line text, secondline;
Getline (text );

Similarly, you can hide the pointer syntax as follows:Copy codeThe Code is as follows: typedef char * pstr;
Int mystrcmp (pstr, pstr );

This will take us to the first typedef trap. The standard function strcmp () has two 'const char * 'parameters. Therefore, it may mislead people to declare mystrcmp () as follows ():Copy codeThe Code is as follows: int mystrcmp (const pstr, const pstr );

Using the GNU gcc and g ++ compiler generates warnings. In order, 'const pstr' is interpreted as 'Char * const' (a pointer constant pointing to char ), the two do not share the same meaning. To obtain the correct type, the following statement should be made:Copy codeThe Code is as follows: typedef const char * pstr;

Purpose 6: simplify the code
Simplified code. 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 statement:Copy codeThe Code is as follows: void (* B [10]) (void (*)());

The variable name is B. Replace pFunParam with the alias in the brackets on the right.Copy codeThe Code is as follows: typedef void (* pFunParam )();

Replace B with the variable on the left, and pFunx with alias 2:Copy codeThe Code is as follows: typedef void (* pFunx) (pFunParam );

The most simplified version of the original statement:Copy codeThe Code is as follows: pFunx B [10];

Original statement:Copy codeThe Code is as follows: doube (*) (* e) [9];

The variable name is e. Replace the left part with pFuny as Alias 1:Copy codeThe Code is as follows: typedef double (* pFuny )();

Replace the variable e on the right, and pFunParamy is alias 2.Copy codeThe Code is as follows: typedef pFuny (* pFunParamy) [9];

The most simplified version of the original statement:Copy codeThe Code is as follows: 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:Copy codeThe Code is as follows: 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.Copy codeThe Code is as follows: 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.

Purpose 7: typedef and storage class specifier)
This is not surprising. typedef is like auto, extern, mutable, static. Like register, it is a storage keyword. This does not mean that typedef will really affect the Storage Feature of objects; it only means that in the statement structure, typedef statements look like static, extern and other types of variable declarations. The following is a second trap:Copy codeThe Code is as follows: typedef register int FAST_COUNTER; // Error

Compilation and translation fail. The problem is that you cannot have multiple storage-class keywords in the Declaration. Because the symbol typedef occupies the storage class keyword, register (or any other storage class keyword) cannot be used in the typedef declaration ).

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.