Using typedef to suppress inferior code (forsilence21037475)

Source: Internet
Author: User

suppressing inferior code with typedef

Author: Dannykalev
Compiling: MTT Studio

Original source: Usingtypedeftocurbmiscreantcode

Summary: TypeDef declarations help create platform-independent types and even hide complex and incomprehensible syntax. In any case, using a typedef can bring unexpected benefits to your code, and you can learn to use typedef to avoid imperfections, making your code more robust.

A typedef declaration, called a TypeDef, creates a new name for an existing type. For example, people often use a typedef to write more beautiful and readable code. The so-called aesthetics, meaning that the typedef can hide clumsy syntax constructs and platform-related data types, thereby enhancing portability and future maintainability. This article will make every effort to uncover the powerful features of the typedef and how to avoid some common pitfalls.


Define type names that are easy to remember
The most common use of a typedef is to create a type name that is easy to remember, and use it to archive the programmer's intent. The type is now declared in the variable name, located on the right side of the ' typedef ' keyword. For example:

Typedefintsize;
This declaration defines a synonym for int, with a name of size. Note that a typedef does not create a new type. It simply adds a synonym to an existing type. You can use size in any context that requires int:
Voidmeasure (SIZE*PSZ);
SIZEARRAY[4];
Sizelen=file.getlength ();
std::vector<size>vs;


A typedef can also mask conforming types, such as pointers and arrays. For example, you don't have to repeatedly define an array of 81 character elements as follows:
CHARLINE[81];
CHARTEXT[81];


Defines a typedef that you can do whenever you want to use an array of the same type and size:
TYPEDEFCHARLINE[81];
Linetext,secondline;
Getline (text);

Similarly, you can hide the pointer syntax as follows:
TYPEDEFCHAR*PSTR;
INTMYSTRCMP (PSTR,PSTR);
This will take us to the first typedef trap. Standard function strcmp () has two parameters of type ' constchar* '. Therefore, it may mislead people to declare mystrcmp () as follows:

INTMYSTRCMP (CONSTPSTR,CONSTPSTR);
This is wrong, in order, ' constpstr ' is interpreted as ' char*const ' (a constant pointer to char), not ' constchar* ' (a pointer to a constant char). This problem is easy to solve:

TYPEDEFCONSTCHAR*CPSTR;
INTMYSTRCMP (CPSTR,CPSTR);/Is right now.
Remember: Whenever you declare a typedef for a pointer, add a const to the final typedef name so that the pointer itself is a constant, not an object.

http://blog.csdn.net/flyxx/


Code simplification
The typedef described above is somewhat like a #define macro, replacing the synonym with its actual type. The difference is that the TypeDef is interpreted at compile time, so the compiler is allowed to deal with text substitutions beyond preprocessor capabilities.
For example:
Typedefint (*PF) (constchar*,constchar*);
This declaration introduces the PF type as synonymous with the function pointer, which has two parameters of the constchar* type and a return value of type int. This typedef is essential if you want to use the following form of a function declaration:

Pfregister (PFPF);
The parameter of the Register () 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. Let me show you how to implement this declaration without a typedef:

int (*register int (*PF) (constchar*,constchar*))
(constchar*,constchar*);
Few programmers understand what it means, let alone the risk of error caused by this convoluted code. Obviously, using typedef here is not a privilege, but a necessity. Skeptics may ask, "OK, does anyone still write this code?" "A quick glance at the header file <csinal> that reveals the signal () function, a function with the same interface.

typedef and Storage Class keywords (storageclassspecifier)
This is not a bit surprising, the TypeDef, like Auto,extern,mutable,static, is a storage-class keyword, as is the register. This is to say that a typedef really affects the storage characteristics of an object; it simply says that the TypeDef declaration looks like a variable declaration of a type such as Static,extern on the composition of the statement. Here's a second trap:

typedefregisterintfast_counter;//Error
compilation does not pass. The problem is that you can't have multiple storage-class keywords in the 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.


Promotion of Cross-platform development
There is another important use of TypeDef, 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 achieve the highest precision:

Typedeflongdoublereal;

On a machine that does not support longdouble, the typedef will look like the following:
Typedefdoublereal;

And, on a machine that does not have a double, the typedef looks like this:
Typedeffloatreal;

Instead of making any changes to the source code, you can compile the application with real type on each platform. The only thing to change is the typedef itself. In most cases, even this tiny change can be done automatically through 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, a typedef like std::string and Std::ofstream hides a long, incomprehensible template-specific syntax,
such as:basic_string<char,char_traits<char>,allocator<char>> and Basic_ofstream<char,char_traits. <char>>.

Author Introduction
Dannykalev is a certified system analyst specializing in C + + and formal language theory of software engineers. He was a member of the C + + standards Committee from 1997 to 2000. He recently completed his master's thesis in the field of general linguistics with outstanding results. In his spare time he enjoys listening to classical music, reading Victorian literature and studying natural languages such as Hittite, Basque and Irishgaelic. Other interests include archaeology and geography. Danny often went to some C + + forums and regularly wrote articles for different C + + websites and magazines. He also teaches programming languages and applied language courses at educational institutions.

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.