High quality c ++/C Programming Guide 1

Source: Internet
Author: User

first of all, Dr. Lin Rui is strongly recommended to read this high-quality C ++/C Programming Guide carefully in an hour or two. You will benefit a lot. My personal harvest records are as follows.
the role of the header file is explained in a few ways:
(1) Use the header file to call the library function. In many cases, Source Code is inconvenient (or inaccurate) to publish to users. You only need to provide users with header files and binary libraries. You only need to follow the interface declaration in the header file to call the library function, without worrying about how the interface is implemented. The compiler extracts the corresponding Code from the library.
(2) Enhanced type security check for header files. If an interface is implemented or used in a different way than the declaration in the header file, the compiler will indicate an error, this simple rule can greatly reduce the burden on Program personnel for debugging and error correction.
In addition, extern can be placed before a variable or function to indicate that the definition of a variable or function is in another file, prompt the compiler to find its definition in other modules when it encounters this variable and function. If the function declaration contains the keyword extern, it only implies that the function may be defined in other source files and has no other function.
Empty rows
A. Empty rows must be added after each class declaration and after each function definition ends.
B. In a function, there are no empty rows in the statements closely related to zookeeper. Separate empty rows in other places. (This article is worth noting)
code line
. one line of code only does one thing, such as defining only one variable or writing only one statement. Such code is easy to read and easy to write comments.
B. If, for, while, do, and other statements occupy one row, the execution statement cannot be followed by the statement. {} Must be added no matter how many statements are executed {}. This prevents writing errors.

For(Initalization; contition; update) {dosomething ();}//Empty rowOther ();

C. initialize the variable whenever possible while defining the variable (proximity principle)

Spaces in the code line

A. leave a space after the keyword, such as const, virtual, inline, case, if, for, and while. Do not leave a space after the function name, followed by the left brace '(', to be different from the keyword.

B. leave a space after the comma and semicolon; "=", "+ =" "> =", "<=", "+", "*", "%", "&", "| ", "<", space should be added before and after the binary operators such as "^"; no space is added before and after the unary operators.

C. There is no space before and after operators such as "[]", ".", and "->.

D. For long for and if statements with expressions, some spaces can be removed for the sake of conciseness.

 
For(I =0; I <10; I ++)//Good style

Long row splitting

The maximum length of a code line should be 70 to 80 characters. A long expression is split into new rows at the lower-priority operator, which is placed at the beginning of the new line (to highlight the operator ). The new lines to be split should be properly indented to make the layout neat and the statement readable.

 
If(Very_longer_variable1> =Very_longer_variable12)& (Very_longer_variable3 <=Very_longer_variable14)& (Very_longer_variable5 <=Very_longer_variable16) {dosomething ();}

Note

A. Note is a "prompt" for the code, not a document. Comments in the program cannot be overwhelming, and too many comments will be dazzled. There are few annotations.

B. Write and annotate the code, modify the code, and modify the corresponding comments to ensure the consistency between the comments and the code.Annotations that are no longer useful must be deleted.

C. Avoid using abbreviations in comments, especially those that are not commonly used.

D. The location of the comment should be adjacent to the described code. It can be placed above or right of the code, not below.

F. When the code is relatively long, especially when multiple nesting occurs, you should add comments at the end of some paragraphs to facilitate reading.

Class Layout

There are two main types of layout:

(1) write private-type data in front and public-type functions in the back. Programmers who use this layout claim the design of the class "data-centric", focusing on the internal structure of the category.

(2) Write Functions of the Public type in front and data of the private type in the back. The programmer who uses this layout claims that the design of the class is "behavior-centric", focusing on the interface (or service) that the class should provide ).

We recommend that you use the "behavior-centered" writing method, that is, first consider the functions that the class should provide.

ClassA {Public:VoidFunc1 (Void);VoidFunc2 (Void);...Private:IntI, J;FloatX, Y ;...}

Common rules

A. identifiers should be intuitive and readable. The length of the identifiers should comply with the "Min-length & Max-Information" principle.

B. The naming Rules should be consistent with the operating system or development tools used.

For example, the identifiers of Windows applications are usually in a case-insensitive manner, such as addchild. The identifier of a Unix application is usually "lowercase and underlined", for example, add_child. Do not mix these two types of styles.

C. The name of a variable should be "noun" or "Adjective + noun"; the name of a global function should be "verb" or "Verb + noun" (verb phrase ).

D. Avoid numerical numbers in the name, such as value1 and value2, unless the number is required logically. This is to prevent programmers from being lazy and refuse to name their brains, resulting in meaningless names (because numbers are the most convenient ).

Simple naming rules for Windows Applications

A. The class name and function name are combined with words starting with an upper-case letter.

B. variables and parameters are combined with words starting with lowercase letters.

C. constants are all separated by uppercase letters and underscores.

D. Add the static variable prefix S _ (indicating static ).

E. If you have to require a global variable, add the global variable prefix G _ (indicating global ).

F. The data member of the class is prefixed with m_( indicating Member). This prevents the data member from having the same name as the parameter of the member function.

G. To prevent conflicts between some identifiers in a software library and other software libraries, you can add prefixes that reflect the nature of software to various identifiers.

If statement

Do not use "=" or "! = "Is compared with any number.

If(X> =-epsinon) & (x <=Epsinon ))//Epsinon indicates the allowable error (accuracy ).

Sometimes we may see such an odd format as if (null = P. The program is not wrong. It is intended to put P and null upside down to prevent if (P = NULL) from being mistakenly written as if (P = NULL. The compiler considers if (P = NULL) as legal, but it indicates that if (null = P) is incorrect because null cannot be assigned a value.

Sometimes, if/else/return combinations are encountered in the program.

 
If(Condition)ReturnX;ReturnY;

Rewrite

If(Condition ){ReturnX ;}Else{ReturnY ;}

Or rewrite it to a more concise

 
Return(Condition? X: Y );

Efficiency of loop statements

In C ++/C loop statements, the for statement is frequently used, while statements are rarely used. The basic way to improve the efficiency of a circular body is to reduce the complexity of the circular body.

In multiple loopsThe longest loop is placed in the innermost layer, and the shortest loop is placed in the outermost layer.To reduce the number of times the CPU switches across the cycle layer.

Switch statement

Do not forget the last default branch. Even if the program really does not need to be processed by default, the statement default: break should be retained. This is not an extra step, but to prevent others from mistakenly thinking that you have forgotten the default processing.

GOTO statement

We advocate less use and careful use of goto statements, rather than disabling them.

Comparison between const and # define

The C ++ language can use const to define constants, or use # define to define constants. However, the former has more advantages than the latter:

(1) const constants have data types, while macro constants do not. The compiler can perform type security checks on the former. However, only character replacement is performed for the latter, and there is no type security check. In addition, replacement may produce unexpected errors (marginal effect ).

(2) Some integrated debugging tools can debug const constants, but cannot debug macro constants.

Suggestion: Use Only const constants in the c ++ program instead of macro constants.

Constants in the class

Sometimes we want some constants to be valid only in the class. Since the macro constants defined by # define are global and cannot be achieved, it is assumed that we should use const to modify data members. The const data member does exist, but its meaning is not what we expected.The const data member is a constant only within the lifetime of an object, but it is variable for the entire class, because the class can create multiple objects, the values of the const data members of different objects can be different.The const data member cannot be initialized in the class declaration. The following usage is incorrect because the compiler does not know what the size value is when the class object is not created.

ClassA {...Const IntSize =100;//An error occurred while initializing the const data member in the class declaration.IntArray [size];//Error, unknown size};

The const data member initialization can only be performed in the initialization table of the class constructor, for example

ClassA {... A (IntSize );//ConstructorConst IntSize ;}; A: (IntSize): size (size)//Initialization table of the constructor{...} A (100);//The size of object A is 100.A B (200);//The size of object B is 200.

How can we create constants that are constant throughout the class? Don't count on the const data member. We should use the enumerated constants in the class. For example

ClassA {...Enum{Size1 =100, Size2 =200};//Enumerated constantIntArray1 [size1];IntArray2 [size2];};

Enumerated constants do not occupy the storage space of objects. They are fully evaluated during compilation.. The disadvantage of an enumerated constant is that its implicit data type is an integer, its maximum value is limited, and it cannot represent a floating point number (such as Pi = 3.14159 ).

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.