Dan
Dan

Reputation: 341

Switch Statement continue

Is the following possible in C++?

switch (value) {
   case 0:
      // code statements
      break;
   case 1:
   case 2:
      // code statements for case 1 and case 2
      /**insert statement other than break here
       that makes the switch statement continue
       evaluating case statements rather than
       exit the switch**/
   case 2:
      // code statements specific for case 2
      break;
}

I want to know if there is a way to make the switch statement continue evaluating the rest of the cases even after it has hit a matching case. (such as a continue statement in other languages)

Upvotes: 1

Views: 1332

Answers (3)

Raymond Array Wang
Raymond Array Wang

Reputation: 196

Yep, just don't put in a break. It will naturally fall down to the other switch statements.

Upvotes: 1

Kerrek SB
Kerrek SB

Reputation: 477378

How about a simple if?

switch (value)
{
case 0:
    // ...
    break;

case 1:
case 2:
    // common code
    if (value == 2)
    {
        // code specific to "2"
    }
    break;

case 3:
    // ...
}

Upvotes: 4

Dietmar Kühl
Dietmar Kühl

Reputation: 153955

Once the case label is decided, there is no way to have the switch continue to search for other matching labels. You can continue to process the code for the following label(s) but this doesn't distinguish between the different reasons why a case label was reached. So, no, there is no way to coninue the selection. In fact, duplicate case labels are prohibited in C++.

Upvotes: 2

Related Questions