C + + typedef usage and #define区别

Source: Internet
Author: User

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. For example: char* PA, PB; The majority does not conform to our intention, it only declares a pointer to a character variable,//and a character variable; The following is possible: typedef char* PCHAR; General use capital PCHAR PA, PB; Possible, while declaring two pointers to character variables 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, it was necessary 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: Structure name Object name, namely: TagPOINT1 P1;

It is too troublesome to think that someone often writes more than one struct, so it is invented: 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, change to: typedef double REAL; On three platforms that are not supported by double, instead: 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*) , variable named a, directly with a new alias Pfun replace a can be: typedef int * (*PFUN) (int, char*); The most simplified version of the original statement: Pfun a[5];

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

3. Original declaration:Doube (*) (*E) [9]; the variable is named E, replace the left part first, Pfuny is alias one: typedef double (*PFUNY) , and replace the right variable E, Pfunparamy is alias two typedef pfuny (*pfunparamy) [9]; the most simplified version of the original declaration: Pfunparamy E;

Understand the "right-left law" available for complex declarations: from the variable name, to the right, then to the left, the direction of the reading is reversed when the parentheses are analyzed, the parentheses are jumped out of the brackets, or the right and left side of the order is followed, so the loop is completed until the entire declaration is parsed. Example: int (*func) (int *p); first find the variable name func, there is a pair of parentheses outside, and the left is an * number, which indicates that func is a pointer; is a function, so func is a pointer to such a function, the function pointer, which has a int* type of formal parameter, 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 pointer 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. For example: First definition: typedef char* PSTR; 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 stored class of keywords (like auto, extern, mutable, static, register, etc.), but it does not really affect the storage characteristics of the object, such as: typedef static INT INT2; The non-row compilation fails with the hint "more than one storage class 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; //const char*

#define PSTR2 char *;

PSTR1 S1, S2;

PSTR2 S3, S4;

In the above variable definition, s1, S2, S3 are defined as char *, and S4 is defined as char, not the pointer variable we expect, the root cause is #define只是简单的字符串替换and the 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 compilation: 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.

defining 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;  //const int

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:

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 a bit like #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);  //callback function

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:

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

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, that is to define machine-independent types, for example, you can define a floating-point type called REAL, 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>>.

C + + typedef usage and #define区别

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.