High-quality C/C++ programming (2)----Programmers must-see series

content

foreword

Chapter two

2.1 Blank line

2.2 Lines of code

2.3 Spaces in lines of code

2.4 Alignment

2.5 Long line split

2.6 Position of modifiers

2.7 Notes


foreword

First of all, I declare that the content of the article is not original, but is derived from the summary of the book "High Quality C/C++ Programming" written by Dr. Lin Rui and added some of my own understanding. Some commonly used rules, some content we can't use in the initial stage, so they are deleted, mainly to reduce everyone's reading burden, this series is to help you write standardized and beautiful code, the following text content About to start!

Before starting the text, let me tell you a shortcut key, ctrl + k + f code is automatically aligned! ! !

Chapter two

2.1 Blank line

Blank lines serve to separate program paragraphs. A decent amount of blank lines (not too much, not too little) will make the layout of the program clearer. Empty lines will not waste memory, but will make the code more readable, more structured, and more beautiful.

Rule 2.1.1 Put a blank line after every class declaration and after every function definition.

Rule 2.1.2 In a function body, no blank lines should be added between logically closely related statements, and blank lines should be added to separate other places.

Example:

函数之间的空行
// 空行 
void Function1(…) 
{ 
 … 
} 
// 空行 
void Function2(…) 
{ 
 … 
} 
// 空行 
void Function3(…) 
{ 
 … 
}
函数内部之间的空行
// 空行
while (condition) 
{ 
 statement1; 
 // 空行
 if (condition) 
 { 
 statement2; 
 } 
 else 
 { 
 statement3; 
 } 
// 空行
 statement4; 
} 

2.2 Lines of code

Rule 2.2.1 A line of code does only one thing, such as defining only one variable, or writing only one statement. Such code is easy to read and easy to write in comments.

Rule 2-2-2 Statements such as if, for, while, and do occupy their own line, and the execution statement shall not follow them. Add {} no matter how many statements are executed. This prevents writing mistakes. (We may only want to execute a statement after the condition at first, but then want to add one or more statements on the original basis, it is easy to forget to add {} at this time)

Example:

int width; // 宽度 
int height; // 高度 
int depth; // 深度

x = a + b; 
y = c + d; 
z = e + f;

if (width < height) 
{ 
dosomething(); 
}

for (initialization; condition; update) 
{ 
dosomething(); 
} 
// 空行 
other();

Recommendation 2.2.1 As far as possible, initialize the variable at the same time as it is defined (proximity principle)

If the variable's reference and its definition are far apart, the initialization of the variable can easily be forgotten. A program error may result if you refer to an uninitialized variable. This recommendation can reduce hidden dangers. Another reason is that the variables we initialize may have some meaning in subsequent conditional judgments.

Example:

int width = 10; // 定义并初绐化 width 
int height = 10; // 定义并初绐化 height 
int depth = 10; // 定义并初绐化 depth

2.3 Spaces in lines of code

Rule 2.3.1 Leave a space after the keyword. At least one space must be left after keywords such as const, virtual, inline, case, etc., otherwise the keywords cannot be parsed. Keywords like if, for, while etc. should be followed by a space followed by an opening parenthesis '(' to highlight the keyword.

Rule 2.3.2 Do not leave a space after the function name, followed by an opening parenthesis '(', to distinguish it from keywords.

Rule 2.3.3 '('followed by, ')', ',', ';' followed by the front, and no space is left. (Following back means no space after it, and following it forward means no space before it)

Rule 2.3.4 Leave a space after ',', such as Function(x, y, z). If ';' is not the end of a line, leave a space after it, such as for (initialization; condition; update).

Rule 2.3.5 Assignment operators, comparison operators, arithmetic operators, logical operators, bit field operators, such as "=", "+=" ">=", "<=", "+", "* ", "%", "&&", "||", "<<", "^" and other binary operators should be preceded and followed by spaces.

Rule 2.3.6 Unary operators such as "!", "~", "++", "--", "&" (address operator), etc. do not add spaces before and after.

Rule 2.3.7 Operators like "[]", ".", "->" should not be preceded and followed by spaces.

Recommendation 2.3.1 For the for and if statements with long expressions, some spaces can be appropriately removed for compactness, such as for (i=0; i<10; i++) and if ((a<=b) && ( c<=d)).

Example:

const int a = 7;

if (year >= 2000) 

for (i=0; i<10; i++) 

x = a < b ? a : b; 

int *x = &y; 

array[5] = 0;

a.Function(); 

b->Function();

2.4 Alignment

Rule 2.4.1 The delimiters '{' and '}' of a program shall be on a line of their own and in the same column, and left-aligned with the statement referencing them.

Rule 2.4.2 Code blocks within { } are left-aligned a number of spaces to the right of '{'.

Example:

void Function(int x) 
{ 
… // program code 
}

if (condition) 
{ 
… // program code 
} 
else 
{ 
… // program code 
}

for (initialization; condition; update) 
{ 
… // program code 
}

While (condition) 
{ 
… // program code 
}

如果出现嵌套的{},则使用缩进对齐,如:
 { 
   … 
      { 
         … 
      } 
   … 
} 
 

2.5 Long line split

Rule 2.5.1 The maximum length of a line of code should be controlled within 70 to 80 characters. The line of code should not be too long, otherwise the eyes will not be able to see it, and it will not be easy to print. Here is a supplement for you to use the line continuation character: use \ in the position where the statement wants to continue the line, and continue to write the code connecting the previous line on the next line.

Example: 

Rule 2.5.2 Long expressions are split into new lines at lower precedence operators, with the operator at the beginning of the new line (to stand out the operator). The split new line should be properly indented to make the typesetting neat and the statement readable.

Example:

if ((very_longer_variable1 >= very_longer_variable12) 
   && (very_longer_variable3 <= very_longer_variable14) 
   && (very_longer_variable5 <= very_longer_variable16)) 
{ 
    dosomething(); 
}

virtual CMatrix CMultiplyMatrix (CMatrix leftMatrix, 
                                 CMatrix rightMatrix);

for (very_longer_initialization; 
     very_longer_condition; 
     very_longer_update) 
{ 
     dosomething(); 
}

2.6 Position of modifiers

Whether the modifiers * and & should be placed near data types or variable names is a matter of debate.

If you put the modifier * close to the data type, for example:

int* x;

Semantically speaking, this way of writing is more intuitive, that is, x is a pointer of type int.

The disadvantage of the above writing method is that it is easy to cause misunderstanding, for example: int* x, y; Here y is easily misunderstood as a pointer variable. While defining x and y on separate lines can avoid misunderstandings, not everyone wants to do it.

Rule 2.6.1 The modifiers * and & should be placed next to variable names.

For example: char *name; int *x, y; // Here y will not be misunderstood as a pointer (of course, this method of defining variables is not recommended for everyone)

2.7 Notes

The comment in C language is "/*...*/". In the C++ language, "/*...*/" is often used for program block comments, and "//..." is generally used for line comments.

Annotations are typically used to:

(1) Version and copyright statement;

(2) Function interface description;

(3) Important code lines or paragraph hints.

Although comments help to understand the code, be careful not to use comments too much.

Rule 2.7.1 Comments are "hints" to code, not documentation. The comments in the program should not be overwhelming, too many comments will make people dazzled. Annotation is less tricky. 

Rule 2.7.2 Comments are unnecessary if the code is already clear.

For example i++; // i plus 1, extra comments

Rule 2.7.3 Write code while commenting, modify code and modify corresponding comments to ensure the consistency of comments and code. Comments that are no longer useful are removed.

Rule 2.7.4 Comments should be accurate and easy to understand to prevent ambiguity. Wrong annotations are not only unhelpful but harmful.

Rule 2.7.5 Try to avoid using abbreviations in comments, especially when abbreviations are not commonly used.

Rule 2.7.6 Comments should be placed adjacent to the code being described, either above or to the right of the code, but not below.  

Rule 2.7.8 When the code is long, especially with multiple nestings, comments should be added at the end of some paragraphs to make it easier to read.

Guess you like

Origin blog.csdn.net/m0_57304511/article/details/121152528