1break statement
Break statements are usually used in loop statements and switch statements. When a break is used to switch a switch statement, the program can jump out of the switch and execute the statement after the switch. If there is no break statement, it will become an endless loop and cannot exit. The usage of break in the switch has been met in the previous example when we introduced the switch statement. Here we will not give an example.
When the break statement is used in do-while, for, and while loop statements, the program can terminate the loop and execute the statements following the loop. Generally, the break statement is always associated with the if statement. That is, the loop jumps out when the conditions are met.
[Example 6.8]
The code is as follows: |
Copy code |
Main () { Int I = 0; Char c; While (1)/* set loop */ { C = '';/* variable initial value */ While (c! = 13 & c! = 27)/* receives characters on the keyboard until you press enter or the Esc key */ { C = getch (); Printf ("% cn", c ); } If (c = 27) Break;/* judge to exit the loop if the Esc key is pressed */ I ++; Printf ("The No. is % dn", I ); } Printf ("The end "); } |
Note:
The break statement does not work for the if-else condition statement.
In a multi-tier loop, a break statement only jumps one layer outward.
6.1.2 continue statement
The continue statement is used to forcibly execute the next loop by skipping the remaining statements in the loop. The continue statement is only used in loop bodies such as for, while, and do-while. It is often used together with the if condition statement to accelerate the loop. The execution process can be shown in the following figure.
1) while (expression 1)
{......
If (expression 2) break;
......
}
2) while (expression 1)
{......
If (expression 2) continue;
......
}
[Example 6.9]
The code is as follows: |
Copy code |
Main () { Char c; While (c! = 13)/* loop if it is not a carriage return */ { C = getch (); If (c = 0X1B) Continue;/* if you press the Esc key and do not output it, perform the next loop */ Printf ("% cn", c ); } } |