Search code examples
c++switch-statementgoto

Is it possible to use goto with switch?


It seems it's possible with C#, but I need that with C++ and preferably cross platform.

Basically, I have a switch that sorts stuff on single criteria, and falls back to default processing on everything else.

Say:

switch(color)
{
case GREEN:
case RED:
case BLUE:
    Paint();
    break;
case YELLOW:
    if(AlsoHasCriteriaX)
        Paint();
    else
        goto default;
    break;
default:
    Print("Ugly color, no paint.")
    break;
}

Solution

  • Not quite but you can do this:

    switch(color)
    {
    case GREEN:
    case RED:
    case BLUE:
         Paint();
         break;
    case YELLOW:
         if(AlsoHasCriteriaX) {
             Paint();
             break; /* notice break here */
         }
    default:
         Print("Ugly color, no paint.")
         break;
    }
    

    OR you could do this:

    switch(color)
    {
    case GREEN:
    case RED:
    case BLUE:
         Paint();
         break;
    case YELLOW:
         if(AlsoHasCriteriaX) {
             Paint();
             break; /* notice break here */
         }
         goto explicit_label;
    
    case FUCHSIA:
         PokeEyesOut();
         break;
    
    default:
    explicit_label:
         Print("Ugly color, no paint.")
         break;
    }