switch_case,&&,| |, conditional operator and comma operator, loop statement

Source: Internet
Author: User
Tags case statement

I. Switch-case

Switch-case statements are mainly used in environments with multi-branch conditions where the use of if statements can be cumbersome and inefficient.

switch (expression)

{

Case Const EXPRESSION1:

....

Case Const expression2;

...

Default

...

}

During execution, the value of expression is compared with the value of each case to implement the function of the switch statement. The keyword case and its associated value are referred to as case labels. the value of each case label must be an integer constant expression , and there cannot be two cases with the same instance label. In addition, there is a special case marking-default marking.

If the value of expression matches one of the case labels, the program executes the individual statements from the first statement following the label until the switch ends or the break statement is encountered, if no case label (and no default label) has occurred ), the program resumes execution from a statement that follows the switch statement.

There is a general misconception about switch: that the program only executes matching case label related statements. This is not actually the case, the label is just the starting point for the program to execute, the program executes from that point, and continues to execute other statements across the case boundary until the switch ends or the break statement is encountered.

The use of the break statement is the core of the Switch-case statement. Because in most cases, a break statement must precede the next case label.

Intentionally omitting break is a particularly rare usage, so be sure to add some comments around this form of code to explain its running logic.

In a switch-case structure, an internal variable can only be defined in the last case label or default. This rule is specified to avoid the occurrence of code skipping variable definitions and initialization.

The reason why this rule exists: If you define a variable, the variable will be valid from this definition until the end of the statement block. If you define a variable in the middle of a two case, you can use this variable for other labels that are later in the argument that defines the variable. But what if switch starts from those subsequent case labels? Perhaps this variable is not defined and used, which we do not want to see. In order to realize the variable can be defined in case, it is possible to introduce the statement block idea. The variable is defined in the block of statements to ensure that the variable is defined and initialized before it is used. The variable is illegal out of this statement block. therefore, in a case statement block, it is best not to define variables, and the required variables should be defined and initialized before the switch. If you must define a variable, be cautious, and implement the definition of an internal variable in a block-by-statement manner.

Defining the default label is still useful for those environments where there are no statements executed under the default label, and defining the default label can clearly tell the reader that this situation has been taken into account, but nothing can be done. The default label cannot exist alone, it must precede the statement, and if switch ends with default and there is no task for the default branch to execute, an empty statement must be added after the default label.

Two. &&,| |

&& | | is the C + + logic or logical AND operator. In the evaluation process, B is only solved if a cannot determine the value of an expression. In the logic and expression, a evaluates to true. If a evaluates to false, no matter what the value of B is, the value of the logical expression is false. When the value of a is true, only the value of B is true, and the value of the logical and expression is true. In logic or in the same way, this is the short-circuit evaluation.

&& and &,| | and | The difference between:& and | is a bit and a bit or an operator. Requires two integer operands. &, at the position of each bit, if the two operand corresponds to a bit of 1, then the bit in the operation result is 1, otherwise 0. | operation, in the position of each bit, if the two operand corresponds to a bit only one is 1, then the result of the operation is 1, otherwise 0; The bitwise operator and the logical operator each differ by | | And the && operator have short-circuit properties, and if the value of the expression is determined by the left operand, then it is no longer evaluated on the right-hand operand. In contrast, the operands on both sides of the | and & operators need to be evaluated.

In C + +, mark the end of a statement. If you accidentally write a semicolon, it may not cause any undesirable consequences. This semicolon may be treated as an empty statement that does not produce any effect, or the extra semicolon is recognized by the compiler, and the compiler generates a warning statement because of this extra semicolon, which you can quickly find and remove, depending on the warning statement. However, after adding a semicolon to the If,for,while statement, the statement immediately following the IF or while clause has no relation to the conditional judgment part. For example

int a = 1;

while (a = = 1);

{

a--;

}

Compile normally, and loop

Also, the lack of semicolons can lead to errors, such as

int arrintmatrix[3] = {0,1,3}

void Main ()

{

int iIndex = 3;

if (iindex<3)

  Return

Arrintmaxtrix[0] = 3;

}

Semicolons indicate the end of a C + + statement, with a semicolon and a semicolon missing can cause undesirable consequences. should be cautious.

Three. Conditional operators and comma operators

The conditional operator is the only "trinocular operator" of the C + + language. It accepts 3 operands, and the operator of the same condition controls the order of evaluation of the expression. Use the following:

Expression1?expression2:expression3; (1)

(expression1)?   (expression2):(expression3); (2)

The precedence of the conditional operator is very low, so its operands, even without parentheses, generally do not cause problems. However, in order to express clarity, it is preferred to put parentheses at both ends of each expression. The expression1 is computed first, and if the value is true, then the value of the entire expression is the value of expression2, and Expression3 is not evaluated. Otherwise, if the value of Expression1 is false, then the value of the entire conditional statement is the value of Expression3, and expression2 is not evaluated.

The comma operator separates two or more expressions, which are evaluated one by one from left to right, while the value of the entire expression is the value of the last expression. Use the following:

Expression1,expression2,expression3,..., expressionn;

each expression in the comma operator is evaluated, and the value of the entire expression is the value of the last expression. Because these expressions are evaluated in a fixed order, they take the order of evaluation from left to right. commonly used in the increment portion of a for statement, that is, if the iteration variable has more than one, it comes in handy, for (int i = 0,j=max;i<=j;++i,--j)

Four. Looping statements

Do not modify the loop variable throughout the for loop to prevent the for loop from losing control, resulting in strange phenomena such as a dead loop

It is recommended that the value of the loop control variable for the For statement be used as a "semi-open half-closed interval" because it is more intuitive.

The X-value belongs to the semi-open half-closed interval "0<=x<n", the interval from start to end is N, the number of cycles is n x value is closed interval "0<=x<=n-1", the interval from start to end is N-1, the number of cycles is n

for (int x=0;x<n;x++) for (int x=0;x<=n-1;x++)//code 1 more intuitive

The For statement uses the most frequently used in A/C + + Loop statement, followed by the while statement. While statements are seldom used.

In multiple loops, if possible, the longest loop should be placed in the outermost layer, and the shortest loop is placed on the outer layer to reduce the number of times the CPU crosses the loop. The reasons are as follows: The longest cycle in the internal can improve the efficiency of I cache, reduce because the loop jump caused cache miss and pipeline flush caused by the delay, many times the same cycle can also improve the success rate of jump prediction, improve pipeline efficiency.

Example 1:for (row = 0;row<100;row++) Example 2:for (row = 0;row<100;row++)

for (col=0;col<5;col++) for (col=0;col<5;col++)

{                            {

sum = Sum+a[row][col]; sum = Sum+a[row][col];

}                            }

Example 1 inefficient, long cycle at the outermost, example 2 high efficiency, long cycle in the most inner layer

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.

Example 3:for (i = 0;i<100;i++) example 4:if (condition)

{                           {

if (condition) for (i = 0;i<100;i++)

DoSomething (); DoSomething ();

else}else

Dootherthing (); {

} for (i = 0;i<100;i++)

DoSomething ();

}

The program in Example 3 performs N-1 logic judgments more than example 4. And because the former always have to make logical judgments, interrupted the circulation "pipeline" operation, so that the compiler can not do the optimization of the loop, reducing the efficiency. If n is very large, it is best to use example 4 to improve efficiency. If n is very small, the efficiency difference between the two is not obvious, the use of example 3 is better. Because the program is more concise.

switch_case,&&,| |, conditional operator and comma operator, loop statement

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.