Summary of C++typedefine Usage

Source: Internet
Author: User

Reprinted from Http://www.cnblogs.com/charley_yang/archive/2010/12/15/1907384.html

First to fourth use

Use one:

Defines an alias for a type, not just a simple macro substitution. Can be used as multiple objects that declare a pointer type at the same time. Like what:
char* PA, PB; The majority does not conform to our intent, it only declares a pointer to a character variable,
and a character variable;
The following are possible:
typedef char* PCHAR; General capitalization
PCHAR PA, PB; It is possible to declare two pointers to a character variable
Although:
Char *pa, *PB;
Also feasible, but relatively not in the form of TypeDef intuitive, especially in the need of a large number of pointers, the way typedef is more convenient.

Use two:

Used in the old C code (specific How old is not checked), to help the struct. In the previous code, when declaring a struct new object, you had to bring a struct with the form: struct struct name Object name, such as:
struct TAGPOINT1
{
int x;
int y;
};
struct tagPOINT1 p1;

In C + +, you can write directly: the name of the struct name object, which is:
TagPOINT1 P1;

It is too much trouble to think that someone often writes a struct, so they invent:
typedef struct TAGPOINT
{
int x;
int y;
}point;

Point P1; This is less than the original way to write a struct, more convenient, especially in the large use of time

Perhaps, in C + +, this use of TypeDef is not very large, but understanding of it, to master the old code is still helpful, after all, we may encounter in the project earlier legacy code.

Use three:

Use typedef to define platform-independent types.
For example, to define a floating-point type called REAL, on the target platform one, let it represent the highest precision type:
typedef long double REAL;
On platform two that does not support long double, replace the following:
typedef double REAL;
On three platforms that are not supported by double, replace the following:
typedef float REAL;
That is, when cross-platform, just change the typedef itself, do not make any changes to other source code.
This technique is widely used by the standard library, such as size_t.
In addition, because typedef defines a new alias for a type, it is not a simple string substitution, so it is more robust than a macro (although using macros can sometimes accomplish the above purposes).

Use four:

Define a new, simple alias for a complex claim. The method is: in the original declaration gradually replaced with the alias part of a complex declaration, so loop, the part with the variable name to the last substitution, get the original declaration of the most simplified version. Example:

1. Original declaration: Int * (*A[5]) (int, char*);
The variable name is a, and replacing a with a new alias Pfun is possible:
typedef int * (*PFUN) (int, char*);
The most streamlined version of the original statement:
Pfun A[5];

2. Original declaration: void (*b[10]) (void (*) ());
The variable name is B, replace the right part in parentheses, and Pfunparam as alias one:
typedef void (*pfunparam) ();
Replace the left variable B,pfunx with the alias two:
typedef void (*PFUNX) (Pfunparam);
The most streamlined version of the original statement:
Pfunx B[10];

3. Original declaration: Doube (*) () (*e) [9];
Variable named E, replace the left part first, Pfuny as alias one:
typedef double (*pfuny) ();
Replace the right variable E,pfunparamy with the alias two
typedef PFUNY (*pfunparamy) [9];
The most streamlined version of the original statement:
Pfunparamy e;

Understand the right-left rule that is available for complex declarations:
From the variable name, first to the right, then to the left, encountered a round bracket to reverse the direction of reading, after the analysis in parentheses out of parentheses, or the first right after the left order, so loop, until the entire declaration analysis is complete. Example:
Int (*func) (int *p);
First find the variable name func, there is a pair of parentheses outside, and the left is a * number, which means that func is a pointer, then jump out of this parenthesis, first look to the right, and also encounter parentheses, which means (*func) is a function, so func is a pointer to such a function, that is, a function pointer, Such functions have a formal parameter of type int*, and the return value type is int.
Int (*func[5]) (int *);
The right side of the Func is a [] operator, stating that Func is an array with 5 elements, and the left side of the Func has a *, stating that the element of Func is a pointer (note that this is not the modifier func, but the func[5], because [] operator precedence is higher than *, and Func is preceded by [] Combined). Jumping out of this parenthesis, looking to the right, and encountering parentheses, the element of the Func array is a pointer to the function type, which points to a function that has a int* type parameter and a return value of type int.

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

Second, two big traps

Trap One:

Remember, TypeDef is a new alias that defines a type, unlike macro, which is not a simple string substitution. Like what:
Define first:
typedef char* PSTR;
And then:
int mystrcmp (const PSTR, const PSTR);

is const PSTR actually equivalent to a const char*? No, it's actually equivalent to char* Const.
The reason is that const gives the entire pointer itself to be constant, that is, to form a constant pointer char* const.
Simply put, remember that when the const and typedef appear together, the typedef will not be a simple string substitution.

Trap Two:

A typedef is syntactically a keyword that stores a class (such as auto, extern, mutable, static, register, and so on), although it does not really affect the storage characteristics of an object, such as:
typedef static INT INT2; Not feasible
The compilation will fail with the hint "more than one storage class has been specified".

The above informationis from: http://blog.sina.com.cn/s/blog_4826f7970100074k.html Red dragon

Third, typedef and #define的区别

Case one:

In general, typedef are better than # define, especially where pointers are available. Take a look at the example:

typedef char *PSTR1;

#define PSTR2 char *;

PSTR1 S1, S2;

PSTR2 S3, S4;

In the variable definition above, S1, S2, S3 are defined as char *, and S4 is defined as char, not the pointer variable we expect, the root cause is that # define is simply a string substitution and a typedef is a new name for a type.

Case TWO:

The compiler will report an error in the following code, do you know which statement is wrong?

typedef char * PSTR;

Char string[4] = "ABC";

const char *P1 = string;

Const PSTR P2 = string;

p1++;

p2++;

It was p2++ that made a mistake. This question reminds us again: TypeDef and # define are different, it is not a simple text substitution. The const PSTR P2 in the above code is not equal to the const char * p2. Const PSTR P2 and const long x are essentially no different, they are read-only restrictions on variables, except that the data type of the variable p2 is defined by ourselves rather than by the intrinsic type of the system. Therefore, the meaning of const PSTR P2 is that the variable P2 with the qualification data type char * is read-only and therefore p2++ error.

Part IV: Using typedef to suppress poor-quality code

Danny Kalev
Compiling: MTT Studio

Source: Using typedef to CURB miscreant Code

Summary: Typedef declarations help to create platform-independent types, and can even hide complex and difficult-to-understand grammars. In any case, using typedef can bring unexpected benefits to your code, and through this article you can learn to use typedef to avoid imperfections and thus make your code more robust.

typedef declaration, referred to as TypeDef, creates a new name for an existing type. For example, people often use typedef to write more aesthetically pleasing and readable code. The so-called aesthetics means that typedef can hide clumsy grammatical constructs and platform-related data types, thus enhancing portability and future maintainability. This article will do its best to uncover the powerful features of typedef and how to avoid some common pitfalls.

Q: How do I create a platform-independent data type that hides clumsy and incomprehensible syntax?

A: Use typedefs to create synonymous words for existing types.

Define easy-to-remember type names
The most common use of TypeDef is to create easy-to-remember type names, which are used to archive programmers ' intentions. The type is in the name of the variable being declared and is located to the right of the ' typedef ' keyword. For example:

typedef int size;

This declaration defines a synonym for int, named size. Note typedef does not create a new type. It simply adds a synonym to the existing type. You can use size in any context that requires an int:

typedef can also mask conforming types, such as pointers and arrays. For example, you do not have to define an array of 81-character elements as follows:

Char Line[81];char text[81];

Define a typedef that can be used whenever you want to use an array of the same type and size:

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 * ' type parameters. Therefore, it may mislead people to declare mystrcmp () as follows:

This is wrong, in order, ' const PSTR ' is interpreted as ' char * const ' (a constant pointer to char) instead of ' const char * ' (pointer to a constant char). This problem is easy to solve:

typedef const CHAR * CPSTR; int mystrcmp (CPSTR, CPSTR); It's right now.

Remember: whenever you declare a typedef for a pointer, you add a const to the final typedef name so that the pointer itself is a constant, not an object.

Code simplification
The typedef behavior discussed above is somewhat like a #define macro, substituting its actual type for synonymous words. The difference is that the TypeDef is interpreted at compile time, so the compiler is able to cope with the text substitution beyond the preprocessor's capabilities. For example:

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

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

PF Register (pf pf);

The parameter of register () is a PF-type callback function that returns the address of a function whose signature is the same as the name previously registered. Take a deep breath. Let me show you how we can implement this statement without a typedef:

Few programmers understand what it means, not to mention the risk of error caused by this convoluted code. Obviously, using a typedef here is not a privilege, but a necessity. Skeptics may ask, "OK, does anyone else write such a code?" , a quick look at the header file that reveals the signal () function <csinal>, a function with the same interface.

typedef and Storage class keywords (storage class specifier)
This is not a bit surprising, typedef like auto,extern,mutable,static, and register, is a storage class keyword. This is to say that the typedef really affects the storage characteristics of the object; it simply says that in the statement composition, the typedef declares a variable declaration that looks like a static,extern type. The following will take you to a second trap:

typedef register INT Fast_counter; Error

Compile pass. The problem is that you cannot have more than one storage class keyword in a declaration. Because the symbol typedef already occupies the location of the storage class keyword, the register (or any other storage class keyword) cannot be used in a typedef declaration.

Promote cross-platform development
typedef has another important purpose, which is to define machine-independent types, for example, you can define a floating-point type called REAL, and on the target machine it can get the highest precision:

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

And, on a machine that is not even supported by a double, the typedef looks like this:

You can compile this application using the REAL type on each platform without making any changes to the source code. The only thing to change is the typedef itself. In most cases, even this tiny change can be done automatically with wonderful conditional compilation. Isn't it? The standard library uses typedef extensively to create such platform-independent types: Size_t,ptrdiff and fpos_t are examples. In addition, typedef like std::string and Std::ofstream also hide long, incomprehensible template-specific grammars, such as: Basic_string<char, Char_traits<char> Allocator<char>> and Basic_ofstream<char, char_traits<char>>.

Summary of C++typedefine Usage

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.