Dart break and continue
In Dart, the break
and continue
statements are control flow statements used within loops (such as for
, while
, and do-while
) to alter the normal flow of execution. They provide ways to manage iterations based on certain conditions.
Break Statement
The break
statement is used to immediately exit a loop or switch statement. When break
is encountered, control is transferred to the statement immediately following the loop or switch.
Syntax
Example of Break Statement
Here’s an example that demonstrates the use of the break
statement:
Explanation
In this example, the loop iterates from 0 to 9. When i
equals 5, the break
statement is executed, causing the loop to terminate immediately. The message "Loop exited." is printed afterward.
Continue Statement
The continue
statement is used to skip the current iteration of a loop and proceed to the next iteration. When continue
is encountered, the remaining statements in the loop body for that iteration are skipped, and control goes back to the loop’s condition check.
Syntax
Example of Continue Statement
Here’s an example that demonstrates the use of the continue
statement:
Explanation
In this example, the loop iterates from 0 to 9. The if
statement checks if i
is even. If it is, the continue
statement is executed, causing the loop to skip the rest of the body for that iteration. As a result, only the odd numbers are printed.
Summary of Differences
- Break Statement: Exits the loop entirely. Control moves to the statement immediately after the loop.
- Continue Statement: Skips the current iteration and moves to the next iteration of the loop. The loop continues to run until the loop's terminating condition is met.
Important Notes
Nesting: Both
break
andcontinue
can be used in nested loops, but they only affect the innermost loop in which they are called.Example:
Conclusion
The break
and continue
statements in Dart provide control over loop execution, allowing you to exit loops or skip iterations based on certain conditions. Understanding how to use these statements effectively can help you create more efficient and readable code when dealing with loops in Dart.