High-quality C ++/C Programming Guide-Chapter 1 expressions and basic statements

Source: Internet
Author: User

Chapter 1 expressions and basic statements

Readers may suspect that even simple things like if, for, while, Goto, and switch should also discuss programming styles. Is it a big question?

I have found manyProgramI myself made a similar mistake by writing expressions and basic statements with implicit errors.

Expressions and statements both belong to the phrase structure Syntax of C ++/C. They seem simple, but there are many hidden risks in use. This chapter summarizes some rules and suggestions for correct use of expressions and statements.

4.1 operator priority
There are dozens of operators in C ++/C. The priority and combination laws of operators are shown in Table 4-1. Note that the priority of the unary operator +-* is higher than that of the corresponding binary operator.

Table 4-1 operator priority and combination Law

Combination of priority Operators
() []->. From left to right
From !~ + + -- Type) sizeof +-* & from right to left
*/% From left to right
Height +-from left to right
<> From left to right
To <<=>> = from left to right
=! = From left to right
Low & from left to right
^ From left to right
│ From left to right
& From left to right
Column │ from right to left
? : From right to left
= + =-= * =/= % = ^= │ = <=> = From left to right

 

[Rule 4-1-1] IfCodeThere are many operators in the row. use parentheses to determine the Operation Sequence of the expression to avoid using the default priority.

Since it is difficult to memorize a Table 4-1, in order to prevent ambiguity and improve readability, brackets should be used to determine the Operation Sequence of the expression. For example:

WORD = (high <8) │ low

If (A │ B) & (A & C ))

4.2 compound expression
Expressions such as a = B = C = 0 are called compound expressions. The reason that compound expressions are allowed is: (1) concise writing; (2)
This improves compilation efficiency. However, you must avoid misuse of compound expressions.

[Rule 4-2-1] Do not write complex compound expressions.

For example:
I = A> = B & C <D & C + F <= G + H; // The compound expression is too complex.

[Rule 4-2-2] do not have a multi-purpose compound expression.

Example: D = (A = B + C) + R;
This expression evaluates both A and D. It should be split into two independent statements:
A = B + C;
D = a + R;

[Rule 4-2-3] Do not confuse compound expressions in the program with true mathematical expressions.

For example:
If (A <B <c) // A <B <C is a mathematical expression rather than a program expression
Does not indicate
If (A <B) & (B <C ))
It is rather confusing.
If (A <B) <C)

4.3 If statement
The IF statement is the simplest and most commonly used statement in C ++/C. However, many programmers write the if Statement by implicit errors. This section uses "compare with zero value" as an example to discuss.

4.3.1 comparison between Boolean variables and zero values

[Rule 4-3-1] Boolean variables cannot be directly compared with true, false, 1, or 0.

Based on the Boolean semantics, the zero value is "false" (marked as false), and any non-zero value is "true" (marked as true ). There is no uniform standard for the true value. For example, Visual C ++ defines true as 1, while Visual Basic defines true.
Defined as-1.

Assuming that the Boolean variable is named flag, the standard if statement for comparing it with the zero value is as follows:

If (FLAG) // indicates that the flag is true.
If (! Flag) // indicates that the flag is false.

Other usage methods are poor, such:
If (flag = true)
If (flag = 1)
If (flag = false)
If (flag = 0)

4.3.2 comparison between Integer Variables and zero values

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

Assume that the integer variable is named value. The standard if statement for comparing it with zero value is as follows:

If (value = 0)
If (value! = 0)

The style of a Boolean variable cannot be imitated.
If (value) // you may misunderstand that value is a Boolean variable.
If (! Value)

4.3.3 comparison between floating point variables and zero values

[Rule 4-3] Do not use "=" or "! = "Is compared with any number.
Please note that both float and double variables have precision restrictions. Therefore, do not use "=" or "! = "To the number, you should try to convert it into the form of"> = "or" <=.
Assume that the floating point variable is named X.

If (x = 0.0) // comparison of implicit errors
Convert
If (x> =-epsinon) & (x <= epsinon ))
Epsinon indicates the allowable error (accuracy ).

4.3.4 comparison between pointer variables and zero values

[Rule 4-4-4] the pointer variable should be "=" or "! = "Is compared with null.

The zero value of the pointer variable is "null" (recorded as null ). Although the value of null is the same as that of 0, they have different meanings. Assume that the pointer variable is named P, and the standard if statement comparing it with zero value is as follows:
If (P = NULL) // Explicit Comparison between P and null emphasizes that p is a pointer variable
If (P! = NULL)
Do not write
If (P = 0) // It is easy to misunderstand that P is an integer variable.
If (P! = 0)
Or
If (p) // It is easy to misunderstand that p is a Boolean variable.
If (! P)

4.3.5 supplementary description of IF Statements
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)
Return X;
Return y;
Rewrite
If (condition)
{
Return X;
}
Else
{
Return y;
}

Or rewrite it to a more concise
Return (condition? X: Y );

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

[4-4-1] if possible, the longest cycle should be placed in the innermost layer, and the shortest cycle should be placed in the outermost layer to reduce the number of times the CPU switches across the cycle layer. For example, Example 4-4 (B) is more efficient than Example 4-4 (.
 
* Example 4-4 (a) Inefficiency: The long loop is in the outermost layer
For (ROW = 0; row <100; row ++)
{
For (COL = 0; Col <5; Col ++)
{
Sum = sum + A [row] [col];
}
}

* Example 4-4 (B) High Efficiency: long loop at the innermost layer
For (COL = 0; Col <5; Col ++)
{
For (ROW = 0; row <100; row ++)
{
Sum = sum + A [row] [col];
}
}

# [4-4-2] If the loop body has a logic judgment and the number of loops is large, it is recommended to move the logic judgment outside the loop body. The program in Example 4-4 (c) executes the N-1 logical judgment more than in Example 4-4 (d. In addition, because the former still requires logical judgment and interrupts the loop "Pipeline" job, the compiler cannot optimize the loop and reduce the efficiency. If n is very large, it is best to use the example 4-4 (d) to improve efficiency. If n is very small, the efficiency difference between the two is not obvious. Use Example 4-4 (c)
Because the program is more concise.

Table 4-4 (c) low efficiency but simple procedure
For (I = 0; I <n; I ++)
{
If (condition)
Dosomething ();
Else
Dootherthing ();
}

Table 4-4 (d) high efficiency but not concise procedures

If (condition)
{
For (I = 0; I <n; I ++)
Dosomething ();
}
Else
{
For (I = 0; I <n; I ++)
Dootherthing ();
}

4.5 For statement loop control variables

[Rule 4-5-1] The loop variable cannot be modified in the for loop to prevent the for loop from being out of control.

[4-5-1] It is recommended that the value of the for statement's cyclic control variable be written in the form of "half-open and half-closed interval.

In Example 4-5 (a), the X value belongs to the semi-open and semi-closed interval "0 = <x <n". The interval from the start point to the end point is N, and the number of cycles is N.
The X value in Example 4-5 (B) belongs to the closed range "0 = <x <= N-1", the interval from the start point to the end is N-1, and the number of cycles is N.
In contrast, Example 4-5 (A) is more intuitive, although the two have the same functions.

Example 4-5 (a) The cyclic variable belongs to the semi-open and semi-closed interval
For (INT x = 0; x <n; X ++)
{
...
}

Example 4-5 (B) the cyclic variable belongs to the closed interval
For (INT x = 0; x <= N-1; X ++)
{
...
}

4.6 switch statement
Why should I switch the if statement?
Switch is a multi-branch selection statement, while if statements have only two branches to choose from. Although you can use nested if statements to achieve multi-branch selection, such programs are lengthy and difficult to read. This is why the switch statement exists.
The basic format of the switch statement is:
Switch (variable)
{
Case value1 :...
Break;
Case value2 :...
Break;
...
Default :...
Break;
}

[Rule 4-6-1] Do not forget to add break at the end of each case statement. Otherwise, multiple branches overlap (unless multiple branches overlap intentionally ).

[Rule 4-6-2] 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.

4.7 GOTO statement
Since advocating structured design, Goto has become a controversial statement. First, because the GOTO statement can be flexibly redirected, without restrictions, it will indeed damage the structural design style. Second, Goto statements often cause errors or risks. It may skip some object construction, variable initialization, and important computing statements, such:

Goto state;
String S1, S2; // skipped by Goto
Int sum = 0; // skipped by Goto
...
State:
...
If the compiler cannot detect such errors, every time a GOTO statement is used, it may leave a hidden risk.

Many people suggest abolishing the C ++/c goto statement to eliminate future risks. But realistically speaking, errors are caused by programmers themselves, not by Goto's faults. At least one GOTO statement can be explicit. It can jump from multiple loops to the outside without writing many break statements. For example
{...
{...
{...
Goto error;
}
}
}
Error:
...

As if the building is on fire, it is too late to go down from the first level of the stairs, you can jump out of the fire pit from the window. Therefore, we advocate less use and careful use of the GOTO statement, rather than disabling it.

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.