Resolve the specific role of the break statement in the c language switch

  • 2020-04-02 01:23:37
  • OfStack

Question:
The function of break in the control of cyclic flow such as for loop, while loop, etc., is to stop the statement after the break, jump out of the loop, and jump out of the loop control body;
What does break do in switch conditional selection without loop control?

Solutions:
1. The execution flow of the switch statement is:
First, calculate the value of the expression in parentheses after the switch, and then compare this value with the constant expression of each case in turn.
If the value of the expression in parentheses is equal to the value of the constant expression after a case, then the statement after the case is executed. When the break statement is encountered after the execution, the switch statement is exited, and the program flows to the next statement of the switch statement.
If the value of the expression in parentheses is not the same as the constant expression after all cases, the statement following default is executed, the switch statement is exited, and the program moves on to the next statement of the switch statement.
In the switch-case statement, multiple cases can share one execution statement, such as:
Case constant expression 1:
Case constant expression 2:
Case constant expression 3:
Statements;
Break;
Thus, the function of case statement can be seen:
The constant expression after the case actually only serves as the statement label, not the conditional judgment, that is, "just the entry label at the beginning of execution".

Therefore, once it matches the value of the expression in parentheses after the switch, it is executed from this label;
And after executing the statement after a case, if there is no break statement, it will automatically enter the next case to continue execution, and no longer judge whether it matches it. The execution will not stop until the break statement is encountered, and the switch statement will be quit.

Therefore, if you want to jump out of the switch statement immediately after a case split, you must add a break statement at the end of the branch.

2. From the above description, it can be seen that the effect of break in the switch conditional selection statement is basically the same as that in the loop control statement:
Do not execute the statement after the break and terminate the exit switch statement;

3. Unlike the continue statement in the loop control, there is no continue statement in the switch conditional selection statement;

Ok problem solved.


Related articles: