What is the purpose of the 'break' statement in C?

QuestionsQuestions8 SkillsProImplement Loops In CSep, 27 2025
0232

The break statement in C is used to terminate the execution of a loop or a switch statement prematurely. Here are the main purposes of the break statement:

  1. Exiting Loops: When used inside loops (such as for, while, or do-while), the break statement immediately exits the loop, regardless of the loop's condition. This is useful when you want to stop the loop based on a specific condition that is checked during the loop's execution.

    Example:

    #include <stdio.h>
    
    int main() {
        for (int i = 0; i < 10; i++) {
            if (i == 5) {
                break; // Exit the loop when i is 5
            }
            printf("%d\n", i);
        }
        return 0;
    }

    In this example, the loop will print numbers from 0 to 4 and then exit when i equals 5.

  2. Exiting Switch Statements: When used inside a switch statement, the break statement prevents the execution from falling through to subsequent cases. Without a break, the program would continue executing the code in the next case(s) until it encounters a break or the end of the switch statement.

    Example:

    #include <stdio.h>
    
    int main() {
        int day = 3;
    
        switch (day) {
            case 1:
                printf("Monday\n");
                break;
            case 2:
                printf("Tuesday\n");
                break;
            case 3:
                printf("Wednesday\n");
                break; // Prevents fall-through
            default:
                printf("Invalid day\n");
        }
        return 0;
    }

    In this example, the output will be "Wednesday" because the break statement prevents the execution from continuing to the default case.

In summary, the break statement is essential for controlling the flow of execution in loops and switch statements, allowing for more flexible and efficient code.

0 Comments

no data
Be the first to share your comment!