Summary of C ++ typedef usage

Source: Internet
Author: User

Purpose 1 and 4

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; // generally, uppercase is used.
Pchar Pa, PB; // feasible. Two pointers pointing to character variables are declared at the same time.
Although:
Char * pA, * pb;
It is also feasible, but it is not intuitive in the form of typedef, especially where a large number of pointers are required, the typedef method is more convenient.

Purpose 2:

It is used in the code of the old C (not checked for many old ones) 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, namely:
Tagpoint1 P1;

It is estimated that it is too troublesome for someone to write another struct, so they invented:
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 when it is used in a large amount.

Maybe, in C ++, typedef is not very useful, but understanding it is helpful for mastering the old code, after all, we may encounter code that was left behind in 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, it is not a simple string replacement, so it is more robust than a macro (although it can do the above when a macro is used ).

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:

1. Original Declaration: int * (* A [5]) (INT, char *);
The variable name is A. replace a with a new alias pfun:
Typedef int * (* pfun) (INT, char *);
The most simplified version of the original statement:
Pfun A [5];

2. 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];

3. 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, start from the right to the left, and then turn the reading direction when it comes to a parentheses. After the analysis in the parentheses, the brackets will jump out of the brackets, or in the order of right to left, until the entire statement is analyzed. 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.

You can also remember two modes:
Type (*) (...) function pointer
Type (*) [] array pointer

Second, two traps

Trap 1:

Remember, typedef defines a new type of alias. Unlike macros, typedef is not a simple string replacement. For example:
First, define:
Typedef char * pstr;
Then:
Int mystrcmp (const pstr, const pstr );

Is const pstr actually equivalent to const char? No, it is actually equivalent to char * Const.
The reason is that const gives the entire pointer itself constant, that is, the constant pointer char * const is formed.
Simply put, remember that when const and typedef appear together, typedef won't simply replace strings.

Trap 2:

Typedef syntax is a storage class keyword (such as auto, extern, mutable, static, register, etc.), although it does not really affect the storage features of objects, such:
Typedef static int int2; // not feasible
Compilation will fail, and the system will prompt "more than one storage class is specified ".

The above information is from:Author of http://blog.sina.com.cn/s/blog_4826f7970100074k.html: chilon

Third, the difference between typedef and # define

Case 1:

Generally, typedef is better than # define, especially when there is a pointer. See the example below:

Typedef char * pstr1;

# Define pstr2 char *;

Pstr1 S1, S2;

Pstr2 S3, S4;

In the preceding variable definition, S1, S2, and S3 are both defined as char *, while S4 is defined as char, which is not the expected pointer variable, the root cause is that # define is a simple string replacement, while typedef is a new name for a type.

Case 2:

In the following code, the compiler reports an error. Do you know which statement is wrong?

Typedef char * pstr;

Char string [4] = "ABC ";

Const char * P1 = string;

Const pstr P2 = string;

P1 ++;

P2 ++;

P2 ++ error. Another reminder is that typedef is different from # define, which is not a simple text replacement. In the above Code, const pstr P2 is not equal to const char * P2. There is no difference between const pstr P2 and const long x in nature. They both impose read-only restrictions on variables, except that the data type of the variable P2 is defined by ourselves rather than the inherent type of the system. Therefore, const pstr P2 indicates that the variable P2 with the Data Type limited to char * is read-only, so P2 ++ is incorrect.

Part 4: Use typedef to suppress inferior code

By Danny Kalev
Compilation: the cell phone number testing Studio

Source: Using typedef to curb miscreant code

Abstract:Typedef statements help you create platform-independent types and even hide complex and incomprehensible syntaxes. In any case, the use of typedef can bring unexpected benefits to the code. Through this article, you can learn to use typedef to avoid missing, so that the code is more robust.

Typedef declaration, or typedef for short, creates a new name for an existing type. For example, typedef is often used to write more beautiful and readable code. The so-called beauty means that typedef can hide clumsy Syntax structures and platform-related data types to enhance portability and future maintainability. This article will do its best to reveal the powerful features of typedef and how to avoid some common traps.

Q: How to Create platform-independent data types and hide clumsy and incomprehensible syntaxes?

A: Use typedefs to create a synonym for an existing type.

Define a type name that is easy to remember
Typedef is used most often to create a type name that is easy to remember and use it to archive the programmer's intent. Type appears in the declared variable name, which is on the right of the ''typedef ''keyword. For example:

typedef int size;

This statement defines an int synonym with the name size. Note that typedef does not create a new type. It only adds a synonym for an existing type. You can use size in any context that requires an int:

void measure(size * psz); size array[4];size len = file.getlength();std::vector <size> vs; 

Typedef can also conceal conforming types, such as pointers and arrays. For example, you do not need to repeatedly define an array with 81 characters 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:

typedef char Line[81]; Line text, secondline;getline(text);

Similarly, you can hide the pointer syntax 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 ():

int mystrcmp(const pstr, const pstr); 

This is incorrect. In order, 'const pstr' is interpreted as 'Char * const' (a constant pointer to Char ), instead of 'const char * '(pointer to constant char ). This problem can be easily solved:

Typedef const char * cpstr; int mystrcmp (cpstr, cpstr); // It is correct now

Remember:Whenever typedef is declared for the pointer, a const must be added to the final typedef name so that the pointer itself is a constant rather than an object.

Simplified code
The typedef behavior discussed above is a bit like the # define macro, which 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. For example:

typedef int (*PF) (const char *, const char *);

This statement introduces the PF type as the synonym of the function pointer. This function has two parameters of the const char * type and a return value of the int type. If you want to use the following form of function declaration, the above typedef is indispensable:

PF Register(PF pf);

The Register () parameter is a PF type callback function that returns the address of a function with the same signature as the previously registered name. Take a deep breath. The following shows how to implement the declaration without typedef:

int (*Register (int (*pf)(const char *, const char *))) (const char *, const char *); 

Few programmers understand what it means, not to mention the risk of errors caused by such obscure code. Obviously, using typedef is not a kind of privilege, but a necessity. Skeptical people may ask, "OK, will someone write such code ?", Quick View The header file of the signal () function <csinal>, a function with the same interface.

Typedef and Storage Class specifier)
This is not surprising. typedef is like auto, extern, mutable, static. Like register, it is a storage keyword. This means that typedef will really affect the Storage Feature of objects. It only means that in the statement structure, the typedef declaration looks like a variable declaration of static, extern, and other types. The following is a second trap:

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 ).

Promote cross-platform development
Another important purpose of typedef is to define machine-independent types. For example, you can define a floating point type called real. On the target machine, it can obtain the highest precision:

typedef long double REAL; 

On a machine that does not support long double, the typedef looks like the following:

typedef double REAL; 

In addition, on a machine that does not support double, the typedef looks like this :,

typedef float REAL; 

You do not need to make any changes to the source code, you can compile this real-type application on each platform. The only change is typedef itself. In most cases, even this tiny change can be automatically implemented through fantastic Conditional compilation. Isn't it? The standard library uses typedef to create such platform-independent types: size_t, ptrdiff, and fpos_t. In addition, typedef such as STD: string and STD: ofstream also hides long, incomprehensible template-specific syntax, such as: basic_string <char, char_traits <char>, allocator <char>
And basic_ofstream <char, char_traits <char>.

From: http://www.cnblogs.com/charley_yang/archive/2010/12/15/1907384.html

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.