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

break;

Example of Break Statement

Here’s an example that demonstrates the use of the break statement:

void main() { for (int i = 0; i < 10; i++) { if (i == 5) { break; // Exit the loop when i equals 5 } print('i: $i'); // Outputs: i: 0, 1, 2, 3, 4 } print('Loop exited.'); // Outputs: Loop exited. }

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

continue;

Example of Continue Statement

Here’s an example that demonstrates the use of the continue statement:

void main() { for (int i = 0; i < 10; i++) { if (i % 2 == 0) { continue; // Skip the even numbers } print('i: $i'); // Outputs: i: 1, 3, 5, 7, 9 } }

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 and continue can be used in nested loops, but they only affect the innermost loop in which they are called.

    Example:

    void main() { for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (j == 1) { continue; // Skips the current iteration of the inner loop when j equals 1 } print('i: $i, j: $j'); // Outputs: i: 0, j: 0; i: 0, j: 2; i: 1, j: 0; i: 1, j: 2; i: 2, j: 0; i: 2, j: 2 } } }

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.