Control Flow
Conditional statement
Control conditional branch and select different branch programs to execute according to different conditions. If the expression value is nonzero, the branch body is executed. It comes in two forms:
Contains only single branch
if
,if conditional_expression {statements}
γContains multiple branches of
if
andelse
,if conditional_expression {statements} else {statements}
.
Note: Conditional statements support ternary conditional operators.
Loop statement
Repeats the statement within the loop for a specified number of times based on the loop condition.
for-loop
statement is supported. Its syntax is for (init_expression; conditional_expression; loop_expression) {statements}
The execution process is:
Calculate the
init_expression
οΌnamely the loop initialization.Calculate the
conditional_expression
.If the result istrue
,the loop bodystatements
are executed, followed by theloop_expression
.If the result is
false
,for-loop
statement terminates. Sequential execution starts with the nextstatement
.
While statement
Repeated execution of a block can be achieved using while. It syntax is similar to if, however the block is repeatedly executed until the condition evaluates to false. If the condition is not true on first execution, then the loop body is never executed:
It is possible to terminate execution of the while statement by using the break
statement. Execution will continue to next statement in the function. Alternatively, continue
will cease execution of the block, but repeat the loop if the condition still holds:
Do While statement
A do { ... } while (condition);
statement is much like the while (condition) { ... }
except that the condition is evaluated after executing the block. This means that the block is always executed at least once, which is not true for while
statements:
Last updated