difference between break and continue statement in C

28 Dec 2022 Balmiki Kumar 0 C Programming

Understanding the Difference: break vs continue Statements in C

Certainly! The break and continue statements are both control flow statements in C that are used within loops (such as for, while, and do-while) to alter the normal flow of execution. However, they serve different purposes and have distinct effects on the loop execution.

1. break Statement:

The break statement is used to immediately terminate the innermost loop (such as for, while, or do-while) or switch statement that contains it. It causes the control to exit the loop or switch and continue with the next statement after the loop or switch block.

Usage:

  • Used to exit loops prematurely when a certain condition is met.
  • Typically used to break out of a loop early based on a specific condition.
C Programming
for (int i = 0; i < 10; i++) {
    if (i == 5) {
        break; // Exit the loop when i reaches 5
    }
    // ... loop body ...
}

2. continue Statement:

The continue statement is used to skip the current iteration of the innermost loop and move to the next iteration. It causes the control to immediately jump to the loop's test condition or increment statement.

Usage:

  • Used to skip a particular iteration of a loop when a specific condition is met.
  • Often used to skip certain iterations to avoid executing certain statements for that iteration.
C Programming
for (int i = 0; i < 10; i++) {
    if (i % 2 == 0) {
        continue; // Skip even iterations
    }
    // ... loop body ...
}

Key Differences:

  1. Functionality:

    • break terminates the entire loop or switch statement and exits it.
    • continue skips the rest of the current iteration and immediately starts the next iteration of the loop.
  2. Control Flow:

    • break jumps out of the loop or switch, while continue skips the current iteration and continues with the next iteration of the loop.
  3. Usage Scenario:

    • Use break when you want to completely exit a loop or switch based on a certain condition.
    • Use continue when you want to skip a specific iteration and move to the next iteration based on a condition.

Table of key differences between the break and continue statements:

Feature break continue
Purpose Exit a loop early Skip a particular iteration of a loop
Can be used with Loops, switch statements Loops only
Skips remaining iterations of the loop? Yes No
Jumps to the next iteration of the loop? No Yes
 
The break and continue statements can be used to write more efficient and concise C code. However, it is important to use them carefully to avoid unexpected behavior.

BY: Balmiki Kumar

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.