Why does C ++ require pauses in switching commands?

advertisements

This question already has an answer here:

  • Switch Statement Fallthrough…should it be allowed? [closed] 12 answers

When writing switch statements in C++, it seems necessary to include a break after every case. Otherwise, the code will continue to run into the next case.

For example:

int x = 1;
switch (x)
{
    case 0:
        std::cout << "x is 0." << std::endl;
    case 1:
        std::cout << "x is 1." << std::endl;
    case 2:
        std::cout << "x is 2." << std::endl;
    default:
        std::cout << "x is neither 0, 1 nor 2." << std::endl;
}

Will return:

>> x is 1.
>> x is 2.

However:

int x = 1;
switch (x)
{
    case 0:
        std::cout << "x is 0." << std::endl;
        break;
    case 1:
        std::cout << "x is 1." << std::endl;
        break;
    case 2:
        std::cout << "x is 2." << std::endl;
        break;
    default:
        std::cout << "x is neither 0, 1 nor 2." << std::endl;
        break;
}

Will return:

>> x is 1.

My question is: If it is necessary to include the break for every case, then why does C++ require it to be explicitly written at all? Why not just break the switch statement after every case by default in C++? Are there any examples when this behaviour may not in fact be desired?


This is for the favour of "falling throught" cases:

switch (x)
{
    case 0:
    case 1:
        std::cout << "x is 0 or 1." << std::endl;
        break;
}

In this example, the case statement is executed if x is either 0 or 1.