Back to course

Control Flow Keywords: break, continue, goto

C Language: 0 to Hero - The Complete Beginner's Guide

Lesson 20: Control Flow Keywords: break, continue, goto

These keywords allow for immediate alteration of the normal sequential execution of loops and switches.

The break Statement

Immediately terminates the innermost switch or loop (for, while, do-while) containing it. Execution resumes at the statement immediately following the terminated structure.

Example: Searching in a Loop

c for (int i = 1; i <= 10; i++) { if (i == 7) { printf("Found 7! Stopping loop.\n"); break; // Exit the loop entirely } printf("Checking %d...\n", i); }

The continue Statement

Skips the rest of the current iteration of the loop and immediately jumps to the next iteration (checks the condition again).

Example: Skipping Even Numbers

c for (int i = 1; i <= 10; i++) { if (i % 2 == 0) { continue; // Skip the printing for even numbers } printf("%d is odd.\n", i); }

The goto Statement (Avoid if Possible)

goto is used to transfer control unconditionally to a specified label within the same function.

Warning: Excessive use of goto makes code complex, hard to debug, and creates 'spaghetti code.' It is generally discouraged except for specific error handling or exiting deep nested loops.

c int error_state = 1; // ... code ... if (error_state) { goto cleanup_error; } // ... more code ...

cleanup_error: printf("Performing cleanup tasks.\n");