Branching Statements

Lesson 2.7: Branching Statements (break, continue, goto)


Branching statements allow you to alter the normal flow of execution within loops or switch statements. In C, the three primary branching statements are break, continue, and goto.  Let's explore each one, starting with the most common and ending with the one that requires caution.


1. The break Statement


Purpose: Terminates the execution of the innermost loop or switch statement and transfers control to the next statement after the loop or switch.


Usage:


In Loops: Immediately exits the loop, regardless of the loop condition.

In Switch Statements: Prevents "fall-through" behavior, ensuring that only the code within the matching case block is executed.

Example (Loop):


C

for (int i = 0; i < 10; i++) {

    if (i == 5) {

        break; // Exit the loop when i becomes 5

    }

    printf("%d ", i); 

}  // Output: 0 1 2 3 4


Example (Switch):

C

int dayOfWeek = 3;

switch (dayOfWeek) {

    case 1:

        printf("Monday\n");

        break; // Prevent fall-through to the next case

    case 2:

        printf("Tuesday\n");

        break;

    // ... other cases

}

2. The continue Statement


Purpose: Skips the rest of the current iteration of a loop and jumps to the next iteration.


Usage: Only within loops (for, while, do-while).


Example:


C

for (int i = 0; i < 10; i++) {

    if (i % 2 == 0) { // Check if i is even

        continue; // Skip even numbers

    }

    printf("%d ", i); 

} // Output: 1 3 5 7 9


3. The goto Statement (Use with Caution!)


Purpose: Transfers control unconditionally to a labeled statement within the same function.

Usage: Generally discouraged in structured programming because it can lead to spaghetti code (code that is difficult to follow).

Syntax:

C

goto label; // Jump to the statement labeled "label"

...

label:      // Label for the goto statement

    // Code to execute after the jump


Example:

C

int i = 0;

start:

    if (i < 5) {

        printf("%d ", i);

        i++;

        goto start; // Jump back to the label "start"

    } 


Important Notes


break and continue are useful for controlling loop execution in a structured way.

goto should be used sparingly and only in situations where it improves clarity or simplifies the code (e.g., breaking out of deeply nested loops). Overuse of goto can make your code hard to understand and maintain.

Modern C programming often emphasizes the use of structured loops and conditional statements to avoid the need for goto.

Let me know if you'd like more examples or specific use cases for branching statements.

Course Syllabus