Basic working method of loop statement
Determine whether to execute loop body by conditional expression
Conditional expressions follow the principle of if statement expressions
do, while, for
The do statement is executed first and then judged, and the loop body is executed at least once
While statement is executed after judgment, the loop body may not be executed
For statement is judged before execution, which is more concise than while
do
{
// loop
}
while(condition);
while(condition)
{
// loop
}
for (int i = 0; condition; i++)
{
// loop
}
The difference between break and continue
break means to terminate the execution of the loop
continue means to terminate this loop and enter the next loop execution;
continue cannot be used in switch statements
The magical effect of do and break
Skip some sections of code that do not need to be executed without causing a memory leak
summary:
for loop first judge before entering the loop body
for loop is suitable for occasions where the number of loops is fixed
The while loop judges before entering the loop body for execution
while loop is suitable for occasions where the number of loops is uncertain
do .. while loop executes the loop body first and then performs condition judgment
do ... while loop executes the loop body at least once