How to interpret a switch structure (with or without break statements)

User Generated

3mvv

Computer Science

Description

in c++

User generated content is uploaded by users for the purposes of learning and should be used following Studypool's honor code & terms of service.

Explanation & Answer

The break statement is used with the conditional switch statement and with the dofor, and while loop statements.

In a switch statement, the break statement causes the program to execute the next statement outside the switch statement. Without a break statement, every statement from the matched case label to the end of the switch statement, including the default clause, is executed.

In loops, the break statement ends execution of the nearest enclosing do, for, or while statement. Control passes to the statement that follows the ended statement, if any.

Within nested statements, the break statement ends only the do, for, switch, or while statement that immediately encloses it. You can use a return or goto statement to transfer control from more deeply nested structures.

Example

The following code shows how to use the break statement in a for loop.

#include <iostream>
using namespace std;

int main()
{
    // An example of a standard for loop
    for (int i = 1; i < 10; i++)
    {
        cout << i << '\n';
        if (i == 4)
            break;
    }

    // An example of a range-based for loop
int nums []{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

    for (int i : nums) {
        if (i == 4) {
            break;
        }
        cout << i << '\n';
    }
}



Anonymous
Great study resource, helped me a lot.

Studypool
4.7
Trustpilot
4.5
Sitejabber
4.4

Similar Content

Related Tags