Analysis of typedef usage

Source: Internet
Author: User

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

How to create platform-independent data types and hide clumsy and incomprehensible syntaxes?

Use typedefs to create a synonym for an existing type.

Define a type name that is easy to remember
Typedef is used to create a type name that is easy to remember and archive it.ProgramMember's intention. 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>;
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 );
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? ", A quick look at the header file that reveals 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 needSource codeWith any modifications, 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>.

 

 

 

 

Author Profile
Danny Kalev is a certified system analyst who specializes in C ++ and formal language theories. He was a member of the C ++ Standards Committee from 1997 to 2000. Recently, he completed his master's thesis on general linguistics with outstanding achievements. In his spare time, he enjoys listening to classical music, reading Victorian literature, and studying natural languages such as Hittite, Basque, and Irish Gaelic. Other interests include archaeology and geography. Danny often goes to some C ++ forums and regularly writes for different C ++ websites and magazines.Article. He also teaches programming languages and application languages at educational institutions.

 

Note: This classic article is chosen from the C & C ++ Developer Forum. Thank you for posting this article by Danny Kalev !!! Let me have the honor to enjoy the wisdom of the master! (Hain)

 

 

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.