High Quality C ++C Programming Guide (Chapter 4 Expression and Basic Sentences)

zhaozj2021-02-17  50

Chapter 4 Expression and Basic Sentences

Readers may doubt: even if IF, for, while, goto, Switch is simple things to explore programming style, is it a big question?

I really think that many programmers write expressions and basic statements with implied errors, I have also made a similar error.

Expressions and statements belong to the phrase structure syntax of C / C. They seem simple, but there are more hidden dangers when used. This chapter summarizes some rules and suggestions for correct use expressions and statements.

4.1 Priority of the operator

There are dozens of operators in C / C language, and the priority of the operator is shown in Table 4-1. Note that the priority of one yuan operator - * is higher than the corresponding binary operator.

priority

Operator

Binding law

From

high

Until

low

row

Column

() [] ->.

from left to right

! ~ - (Type) SIZEOF

- * &

from right to left

* /%

from left to right

-

from left to right

<< >>

from left to right

<=>> =

from left to right

==! =

from left to right

&

from left to right

^

from left to right

|

from left to right

&&&&

from left to right

||

from right to left

?:

from right to left

= = - = * = / =% = & = ^ =

| = << = >> =

from left to right

Table 4-1 Priority and Combination Law of Operators

l [Rules 4-1-1] If the operator in the code line is more, use parentheses to determine the order of operation of the expression, avoid using the default priority.

Because the Table 4-1 is more difficult, in order to prevent ambiguity and improve readability, the order of operation of the expression should be determined using parentheses. E.g:

Word = (high << 8) | LOW

IF ((A | B) && (A & C))

4.2 composite expression

As a expression of A = B = C = 0 is called a composite expression. The reason for allowing composite expressions is: (1) Clearing is simple; (2) can improve compilation efficiency. But to prevent abuse of composite expressions.

l [Rule 4-2-1] Do not write too complex composite expressions.

E.g:

i = a> = B && c

l [Rule 4-2-2] Do not have multiple use composite expressions.

E.g:

D = (a = b c) R;

This expression is given to a value of a value. Should be split into two independent statements:

A = B C;

D = a r;

l [Rule 4-2-3] Do not confuse the composite expression in the program with "real mathematical expressions".

E.g:

IF (a

Not expressed

IF ((a

Instead, it has become a puzzling

IF ((a

4.3 IF statement

The IF statement is the simplest, most common statement in the C / C language, but many programmers write IF statements in a hidden error. This section takes discussion to discuss this section with "comparison with zero value".

4.3.1 Boolean variables and zero values ​​L [Rules 4-3-1] Do not compare the Boolean variables directly with TRUE, FALSE or 1, 0.

According to the semantics of the Boolean, the zero value is "false" (written as false), any non-zero value is "true" (recorded by true). What is the value of TRUE does not have a unified standard. For example, Visual C defines TRUE to 1, and Visual Basic defines TRUE as -1.

Suppose the Boolean variable name is FLAG, it is compared with the zero value, the standard IF statement is as follows:

IF (flag) // indicates that Flag is true

If (! flag) // means flag is false

Other usage belong to a bad style, for example:

IF (Flag == True)

IF (Flag == 1)

IF (Flag == False)

IF (Flag == 0)

4.3.2 Integer variables and zero value

l [Rule 4-3-2] The integer variable should be compared to 0 with "==" or "! =".

Assuming the name of the integer variable is Value, it is the standard IF statement compared to zero value as follows:

IF (value == 0)

IF (value! = 0)

Written in the style of imitation of the Boolean variable

If (value) // will misunderstand value is a Boolean variable

IF (! value)

4.3.3 Comparison of floating point variables and zero values

l [Rule 4-3-3] Do not compare floating point variables with "==" or "! =" and any number.

Need to pay attention, whether Float is also a Double type variable, it has precision restrictions. Therefore, be sure to avoid "==" or "! =" And digital comparisons, should be triggered into "> =" or "<=" form.

Assume that the name of the floating point variable is x, it should

IF (x == 0.0) // Comparison of incorrect errors

transform into

IF ((x> = - EPSINON) && (x <= epinon))

Where EPSINON is allowed (ie, accuracy).

4.3.4 Pointer variables and zero value comparison

l [Rule 4-3-4] The pointer variable should be compared to NULL with "==" or "! =" and NULL.

The zero value of the pointer variable is "empty" (recorded as null). Although the value of NULL is the same as 0, the meaning is different. Suppose the name of the pointer variable is P, which is the standard IF statement compared to zero value as follows:

IF (p == null) // P and NULL explicitly compared, emphasizing P is a pointer variable

IF (p! = null)

Don't write

IF (p == 0) // Easy to misunderstand P is integer variable

IF (p! = 0)

or

IF (p) // Easy to misunderstand P is Boolean variable

IF (! p)

4.3.5 Supplementary description of the IF statement

Sometimes we may see if (null == p) so weird format. It is not the wrong program, which is the programmer to prevent P and NULL to reverse P and NULL in order to prevent IF (p == null) from being written into IF (p = null). The compiler believes that if (p = null) is legal, it will indicate that if (null = p) is wrong because NULL cannot be assigned.

The combination of IF / ELSE / RETURN is sometimes encountered in the program, and the procedure of the following bad style should be

IF (condition)

Return X;

Return Y;

Rewrite

IF (condition)

{

Return X;

}

Else

{

Return Y;

}

Or rewritten into more concise

RETURN (CONDition? x: y);

4.4 Efficiency of cyclic statements

In the C / C cycle statement, the FOR statement uses the highest frequency, and the While statement is second, the DO statement is rarely used. This section focuses on the efficiency of the cyclic body. The basic approach to improving the efficiency of cyclic body is to reduce the complexity of the circulation.

l [Recommendation 4-4-1] In multiple cycles, if possible, the longest cycle should be placed in the innermost layer, and the shortest cycle is placed in the outermost layer to reduce the number of CPUs cross-cutting cycles. For example, the efficiency ratio of Example 4-4 (b) is higher than the example 4-4 (a).

For (ROW = 0; ROW <100; Row ) {for (COL = 0; Col <5; Col ) {SUM = SUM A [ROW] [col];}}

For (COL = 0; Col <5; COL ) {for (row = 0; ROW <100; ROW ) {SUM = SUM A [ROW] [col];}}

Example 4-4 (a) Low Efficiency: Long cycle in the outermost example 4-4 (b) High efficiency: long cycle in the innermost layer

l [Recommendation 4-4-2] If there is a logic judgment in the circulation, the number of cycles is large, the logic is appropriately moved to the outside of the cyclic body. Example 4-4 (c) of the program is multi-1 logic judge more than the example 4-4 (d). And because the former is logical judgment, the loop "pipeline" operation is interrupted, so that the compiler cannot optimize the loop, reducing efficiency. If N is very large, it is best to use the writing of Example 4-4 (d) to improve efficiency. If N is very small, the difference between the two is not obvious, and the writing method of Example 4-4 (c) is better because the program is more concise.

For (i = 0; i

{

IF (condition)

DOSMETHING ();

Else

Doothershing ();

}

IF (condition)

{

For (i = 0; i

DOSMETHING ();

}

Else

{

For (i = 0; i

Doothershing ();

}

Table 4-4 (c) Low efficiency but program simplicity table 4-4 (d) is high, but the program is not simple

4.5 Loop control variable for for statement

l [Rules 4-5-1] Do not modify the loop variables in the FOR cycle to prevent the FOR cycle from being lost.

l [Recommendation 4-5-1] It is recommended to use the value of the loop control variable of the FOR statement to be written in "semi-open semi-closed interval".

The X value in Example 4-5 (a) belongs to the semi-open semi-closed interval "0 =

The X value in Example 4-5 (b) belongs to the closed interval "0 =

In contrast, examples 4-5 (a) are more intuitive, although the functions of both are the same.

For (int x = 0; x

{

...

}

For (int x = 0; x <= n-1; x )

{

...

}

Example 4-5 (a) The cyclic variable belongs to the semi-open semi-closed interval example 4-5 (b) cyclic variable belongs to the closed section 4.6 Switch statement

Is there a Switch statement in the IF statement?

Switch is a multi-branch selection statement, while if the IF statement is available for selection. Although multi-branch selection can be implemented with nested IF statements, the programs are long-term difficulty. This is the reason for the Switch statement.

The basic format of the Switch statement is:

Switch (variable)

{

Case Value1: ...

Break;

Case Value2: ...

Break;

...

DEFAULT: ...

Break;

}

l [Rule 4-6-1] Each CASE statement does not forget to add BREAK, otherwise multiple branch overlaps (unless intentionally makes multiple branches overlap).

l [Rule 4-6-2] Don't forget the last default branch. Even if the program really does not need Default processing, the statement Default: Break should also be reserved. Do not do more, but to prevent others from mistaken to think that you forgot DEFAULT.

4.7 GOTO statement

Since advocating structured design, Goto has become a controversial statement. First, because the goto statement can be flexibly jump, if it is not restricted, it does destroy the structured design style. Second, the GOTO statement often brings errors or hidden dangers. It may skip some of some objects, initialization of variables, important calculations, etc., for example:

Goto State;

String S1, S2; // Skip by GOTO

Int sum = 0; // Skip by GOTO

...

State:

...

If the compiler can't find such errors, every GOTO statement may leave a hidden danger.

Many people recommend abolishing C / C's goto statement, in order to suffer. But seeking truth from facts, error is caused by programmers, not goto's fault. At least one of the GOTO statements, can be jumped from the middle of the multi-cycle body, and don't write a lot of BREAK statements; for example

{...

{...

{...

Goto error;

}

}

}

Error:

...

Just like the fire is in fire, I will not go down from the first level of the stairs to jump out of the fire pit from the window. So we advocate less, cautious with GOTO statements, not disabled.

转载请注明原文地址:https://www.9cbs.com/read-28726.html

New Post(0)