"C++/C High quality Programming Guide" notes

Source: Internet
Author: User
Tags case statement compact naming convention

  

Review:

C + + High-quality programming Guide;

"Rule 1-2-1" in order to prevent the header file from being repeatedly referenced, a preprocessing block should be generated with the IFNDEF/DEFINE/ENDIF structure.

"Rule 1-2-2" uses the #include <filename.h> format to refer to the header files of the standard library (the compiler will start searching from the standard library directory).

"Rule" uses the #include "filename.h" format to refer to the header file of a nonstandard library (the compiler will start searching from the user's working directory).

"Recommendation 1-2-1" header file contains only "declarations" without "definition"

The "rule 2-2-1" line of code only does one thing, such as defining only a variable, or just writing a single statement. Such code is easy to read and easy to write comments. ( I do not agree with the appendix question while ((*strdest++ = * strsrc++)! = ') ') the wording or separate writing readability will be better, I think the separate write should be more readable .

"Rule 2-2-2" if, for, while, do, and so on the statement from the row, the execution statement must not follow immediately thereafter. Add {} No matter how many statements are executed. This will prevent writing errors.

Recommendation 2-2-1 Initialize the variable as much as possible while defining the variable (nearest principle) if the variable's reference is far apart from its definition, the initialization of the variable is easily forgotten. If you reference a variable that is not initialized, you may cause a program error. This recommendation can reduce the risk.

Leave a blank after the "rule 2-3-1" keyword. Like const, virtual, inline, case and so on at least one space after the keyword, otherwise cannot discriminate keywords. After keywords like if, for, and while, leave a space followed by the left Parenthesis ' (') to highlight the keyword.

Do not leave spaces after the "rule 2-3-2" function name, followed by the left Parenthesis ' ('), as distinguished from the keyword.

"Rule 2-3-3" ' (' back immediately, ') ', ', ', '; ' Move forward, followed by a blank space.

"Rule 2-3-4" ', ' after which you want to leave spaces, such as function (x, y, z). if '; ' is not a line ending symbol, its

After you leave a blank, such as for (initialization; condition; update).

"Rule 2-3-5" assignment operator, comparison operator, arithmetic operator, logical operator, bit field operator,

such as "=", "+ =" ">=", "<=", "+", "*", "%", "&&", "| |", "<<", "^" should be preceded by a space before and after the two-dollar operator.

"Rule 2-3-6" unary operators such as "!", "~", "+ +", "--", "&" (address operator) are not preceded by spaces.

"Rule 2-3-7" such as "[]", ".", "and" such operators before and after the space is not added.

"Recommendation 2-3-1" for statements with long expressions and if statements, some spaces, such as for (i=0; i<10; i++) and if ((a<=b) && (C<=d)), can be suitably removed for the sake of compactness.

The delimiter ' {' and '} ' of the ' rule 2-4-1 ' program should have a single row and be in the same column, with the statement that references them left-justified.

Code blocks within the "rule 2-4-2" {} are left-aligned at the right-hand side of ' {'.

The maximum length of the "rule 2-5-1" code line should be within 70 to 80 characters. The line of code should not be too long, otherwise the eyes can not see, it is not easy to print.

The "rule 2-5-2" long expression is split into a new line at the low-priority operator, and the operator is placed at the top of the new line (so that the operator is highlighted). The new rows to be split are indented appropriately, making the layout tidy and the statements readable.

"Rule 2-6-1" should have modifiers * and & close to variable names

The "rule 2-7-1" comment is a "hint" to the code, not a document. The notes in the program are not distracting and the comments are too many to dazzle. There are fewer tricks to note.

"Rule 2-7-2" if the code is clear, you do not have to comment. Otherwise superfluous, boring. For example

i++; I plus 1, extra notes

The "rule 2-7-3" side writes the code side comment, modifies the code simultaneously modifies the corresponding annotation, guarantees the annotation and the code consistency. Comments that are no longer useful are to be deleted.

The "rule 2-7-4" comment should be accurate and understandable, preventing comments from being two semantic. Wrong comments are not only useless but harmful.

"Rule 2-7-5" try to avoid abbreviations in comments, especially those that are not commonly used.

The location of the "rule 2-7-6" comment should be adjacent to the code described, which can be placed above or to the right of the code and not placed below.

"Rule 2-7-8" when the code is relatively long, especially when there are multiple nesting, it should be at the end of some paragraphs to be released, easy to read. ( this is where many editors like source Insight show the end of a paragraph)

The "rule 3-1-1" identifier should be intuitive and can be spelt, and hopefully the text will be understood without having to "decode" it.

The length of the "rule 3-1-2" identifier should conform to the "Min-length && max-information" principle.

The rule 3-1-3 naming convention is as consistent as possible with the style of the operating system or development tool being used. ( such as the naming of the API in the glib library that mimics the Linux call, the interface that mimics the implementation of its own operating system should be consistent with the prototype so that the API's description is not re-viewed when developing the calling API )

A similar identifier that is only case sensitive is not present in the "Rule 3-1-4" program.

The exact same local and global variables are not present in the "Rule 3-1-5" program, although the scope of the two is different and there is no syntax error, but it can be misleading.

The name of the "rule 3-1-6" variable should use "noun" or "adjective + noun".

The name of the "rule 3-1-7" global function should use "verb" or "verb + noun" (moving-in phrase). The member function of a class should use only "verbs", and the omitted noun is the object itself.

"Rule 3-1-8" uses the correct antonyms group to name variables with mutually exclusive meanings or functions that have opposite actions.

"Recommendation 3-1-1" Try to avoid the number of digits in the name, such as Value1,value2, unless the number is logically required. This is to prevent programmers from slacking off, and not to use their brains to produce meaningless names (because the number of numbers is the most convenient).

The "rule 3-2-1" class name and function name are combined with words that begin with uppercase letters.

The "rule 3-2-2" variable and argument are combined with a word that starts with a lowercase letter.

The "rule 3-2-3" constants are all capitalized letters, with underscores for dividing words.

The "rule 3-2-4" static variable is prefixed with S_ (representing static).

"Rule 3-2-5" if a global variable is required, prefix the global variable with g_ (representing global).

The data members of the "rule 3-2-6" class are prefixed with m_ (for member), which prevents the data member from having the same name as the parameter of the member function.

"Rule 3-2-7" to prevent conflicts in some of the identifiers and other repositories in a software library, you can add prefixes that reflect the nature of the software for a variety of identifiers. For example, all library functions for the three-dimensional graphics standard OpenGL begin with GL, and all constants (or macro definitions) begin with GL. ( the namespace is not well implemented in C, in order to prevent the same strong symbol redefinition from being called in the third-party library, the basic is to avoid it by prefixing, otherwise it will be required to regenerate the library)

"Rule 4-2-1" do not write complex expressions that are too complicated.

For example:

i = a >= b && c < d && C + F <= g + H; Compound expressions are too complex

"Rule 4-2-2" do not have multi-purpose compound expressions.

For example:

D = (A = B + c) + R; The expression asks for both A and D values.

"Rule 4-2-3" do not confuse a compound expression in a program with a "true mathematical expression".

"Rule 4-3-1" does not compare Boolean variables directly with True, false, or 1, 0.

"Rule 4-3-2" should use the integer variable with "= =" or "! = "Compare directly with 0.

"Rule 4-3-3" cannot use a floating-point variable with "= =" or "! = "Compared to any number.

(float or double is defined in the minimum specification and can be viewed )

Be aware that there is a precision limit for variables of either float or double type. So be sure to avoid using the floating-point variable "= =" or "! = "In comparison with numbers, you should try to convert them into" >= "or" <= "forms. Assuming that the name of the floating-point variable is x, you should compare the IF (x = = 0.0)//Implied error

Convert to if ((X>=-epsinon) && (X<=epsinon)) where Epsinon ( should be epsilon, the word in the book is wrong ) is the allowable error (i.e. precision).

"Rule 4-3-4" should use the pointer variable "= =" or "! = "Compared to NULL.

"Recommendation 4-4-1" in multiple loops, if possible, the longest loop should be placed in the topmost layer, the shortest loop is placed at the outermost level, to reduce the number of times the CPU crosses the loop layer.

"Recommendation 4-4-2" If there is a logical judgment in the loop and the number of cycles is large, it is advisable to move the logical judgment out of the loop body.

"Rule 4-5-1" does not modify the loop variable in the For loop body to prevent the for loop from losing control.

Recommendation 4-5-1 recommends that the value of the loop control variable for the For statement be used as the "half open half-closed interval" notation.

"Rule 4-6-1" do not forget to add a break at the end of each case statement, otherwise it will cause multiple branches to overlap (unless you intentionally overlap multiple branches).

"Rule 4-6-2" Don't forget the last default branch. Even if the program really does not need default processing, it should keep the statement default:break; This is not superfluous, but to prevent others from mistakenly thinking that you have forgotten the default processing.

Many people suggest abolishing C++/C's goto statement, abortions. But to be realistic, mistakes are made by programmers themselves, not by the mistakes of Goto. (I've seen an open source protocol stack that uses Goto to error, but it's only used in this place, so use the goto statement sparingly, not disable it)

"Rule 5-1-1" try to use meaning-intuitive represented to represent numbers or strings that will appear more than once in a program. ( named variables are const and macros )

"Rule 5-2-1" uses only const constants in C + + programs without using macro constants, that is, const constants completely replace macro constants.

"Rule 5-3-1" need to be exposed to the constant in the header file, do not need to be exposed to the external constants in the definition file header. For ease of management, the constants of different modules can be centrally stored in a common header file.

"Rule 5-3-2" if a constant is closely related to other constants, you should include this relationship in your definition, rather than giving some orphaned values.

The "rule 6-1-1" parameter should be written in a complete, not easy-to-write parameter type and omit the parameter name. If the function has no arguments, it is filled with void.

The "rule 6-1-2" parameter should be named appropriately and the order should be reasonable. (The code is good, the parameters are divided into, out, in_out, can be read in the book How to say )

"Rule 6-1-3" if the parameter is a pointer and is only used for input, you should add a const to the type to prevent the pointer from being accidentally modified in the function body.

"Rule 6-1-4" if the input parameter passes the object as a value, it should be passed in a "Const &" way, which saves the construction and destruction of the temporary object, thus improving efficiency.

"Recommendation 6-1-1" to avoid the function has too many parameters, the number of parameters as far as possible to control within 5. If there are too many parameters, it is easy to mistake the type or order of the parameters when used. ( generally the first 4 parameters are stored in the register, more than 4 are stored in the stack, less than equals 4 parameters of the function will be faster to take parameters )

"Recommendation 6-1-2" Try not to use parameters of type and number uncertainties.

"Rule 6-2-1" do not omit the type of the return value.

The name of the "rule 6-2-2" function is semantically non-conflicting with the return value type.

"Rule 6-2-3" do not mix the normal values and the error flags back together. The normal value is obtained with an output parameter, and the error flag is returned with a return statement.

"Recommendation 6-2-1" Sometimes the function does not originally need to return a value, but in order to increase flexibility, such as support chain expression, you can append the return value.

"Recommendation 6-2-2" If the return value of a function is an object, there are occasions when "pass by reference" replaces "value passing" to improve efficiency. Some situations can only be passed with "value" and not "referenced", otherwise an error occurs.

"Rule 6-3-1" in the function body "entrance", the validity of the parameters are checked. ( If all functions are checked for validity, it will inevitably reduce efficiency, the data can be divided into external, internal, external data must be checked for validity, internal data can not be checked for validity )

"Rule 6-3-2" checks the correctness and efficiency of the return statement at the "exit" of the function body.

The "Suggest 6-4-1" function has a single function and does not design multipurpose functions.

The "recommendation 6-4-2" function body is small in size, as much as possible within 50 lines of code.

"Recommendation 6-4-3" try to avoid functions with "memory" function. The same input should produce the same output.

"Recommendation 6-4-4" Not only checks the validity of input parameters, but also examines the validity of variables entering the function body through other means, such as global variables, file handles, and so on.

The return value of "recommendation 6-4-5" for error handling must be clear, making it difficult for users to ignore or misunderstand the error condition.

"Rule 6-5-1" uses assertions to catch illegal situations that should not occur. Do not confuse the difference between the illegal situation and the wrong situation, the latter being inevitable and must be dealt with.

"Rule 6-5-2" at the entrance of the function, use assertions to check the validity of the parameters (legitimacy).

"Recommendation 6-5-1" When writing a function, repeat the examination and ask: "What assumptions do I intend to make?" Once the assumptions have been determined, the assumptions are checked using assertions.

"Recommendation 6-5-2" The general textbook encourages programmers to make error-proof designs, but keep in mind that this style of programming may conceal errors. If the "impossible" thing does happen when the error-proof design is in progress, use an assertion to alarm.

After "rule 7-2-1" has requested memory with malloc or new, you should immediately check that the pointer value is NULL. Prevents the use of memory with a pointer value of NULL.

"Rule 7-2-2" do not forget to assign an initial value to both arrays and dynamic memory. Prevents memory that is not initialized from being used as the right value.

"Rule 7-2-3" avoids array or pointer subscript out of bounds, especially beware of "more than 1" or "1 less" operations.

"Rule 7-2-4" the request and release of dynamic memory must be paired to prevent a memory leak.

After "rule 7-2-5" has freed memory with free or delete, the pointer is immediately set to NULL to prevent the "wild pointer" from being produced.

Char * Const P = "word", read-only constant area not allowed to be modified

Note that when an array is passed as an argument to a function, the array is automatically degraded to a pointer of the same type.

"Rule 11-2-1" do not blindly pursue the efficiency of the program, should be satisfied with the correctness, reliability, robustness, readability and other quality factors under the premise of trying to improve the efficiency of the program.

"Rule 11-2-2" to improve the overall efficiency of the program-based, improve local efficiency as a supplement.

"Rule 11-2-3" in optimizing the efficiency of the program, you should first identify the "bottleneck" to limit efficiency, do not optimize in the insignificant.

"Rule 11-2-4" optimizes the data structure and algorithm before optimizing the execution code.

"Rule 11-2-5" Sometimes the time efficiency and space efficiency may be opposite, at this time should analyze that more important, make the appropriate compromise. For example, more memory is spent to improve performance.

"Rule 11-2-6" do not pursue compact code, because compact code does not produce efficient machine code.

"Recommendation 11-3-1" Beware of writing errors on visually indistinguishable operators. We often mistakenly write "=" as "=", such as "| |", "&&", "<=", ">=" such symbols are also prone to "lost 1" error. However, compilers do not necessarily automatically indicate such errors.

The "Recommended 11-3-2" variables (pointers, arrays) should be initialized immediately after they are created to prevent the uninitialized variables from being used as rvalue values.

"Recommendation 11-3-3" Beware of variable initial value, default error, or insufficient precision.

"Recommendation 11-3-4" Beware of errors in data type conversions. Try to use explicit data type conversions (let people know what's going on), and avoid letting the compiler quietly make implicit data-type conversions.

"Recommendation 11-3-5" Beware of variable overflow or underflow, array subscript out of bounds. ( compilation options like VC, gcc compiler stack Overflow protection are all for overflow detection )

"Recommendation 11-3-6" Beware of forgetting to write error handlers, and beware of errors in the error handlers themselves.

"Recommendation 11-3-7" Beware of file I/O errors.

"Recommendation 11-3-8" avoids writing very high-skilled code.

"Recommendation 11-3-9" Do not design a data structure that is exhaustive and flexible. ( flexibility corresponds to increased complexity )

"Recommendation 11-3-10" If the original code quality is better, try to reuse it. But don't fix bad code, you should rewrite it.

"Recommendation 11-3-11" Use standard library functions as much as possible, and do not "invent" library functions that already exist.

"Recommendation 11-3-12" Try not to use variables that are closely related to a specific hardware or software environment.

"Recommendation 11-3-13" Sets the compiler's selection to the strictest state.

"Recommendation 11-3-14" Use tools such as Pc-lint, Logiscope for static code review, if possible.

"C++/C High quality Programming Guide" notes

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.