C programming - break Statement

https:/‮www/‬.theitroad.com

In C programming, the break statement is used to immediately exit a loop or switch statement, and transfer control to the statement immediately following the loop or switch statement.

The break statement is typically used in conjunction with conditional statements such as if, while, for, and switch. When the break statement is executed inside a loop or switch statement, the program will immediately exit that statement and continue executing the statements after it.

Here's the basic syntax of the break statement:

while (condition)
{
    // statements to be executed
    if (some_condition)
    {
        break;
    }
}

In this example, if some_condition evaluates to true, the break statement will be executed and the program will exit the while loop.

Here's another example of using the break statement with a switch statement:

int num = 2;
switch (num)
{
    case 1:
        printf("The number is 1.\n");
        break;
    case 2:
        printf("The number is 2.\n");
        break;
    case 3:
        printf("The number is 3.\n");
        break;
    default:
        printf("The number is not between 1 and 3.\n");
        break;
}

In this example, the switch statement checks the value of num, and executes the appropriate case statement based on the value. If num is equal to 2, the program will print "The number is 2." and then immediately exit the switch statement using the break statement.

It's important to note that the break statement should only be used within loops or switch statements, and not in other contexts such as functions or if statements. Using the break statement in the wrong context can result in unexpected behavior or errors.