Search code examples
c++switch-statementgoto

C++ switch statement - jump between cases


In C++, can I do something like the code below?

In a specific case, if some conditions are met, can I jump to another case?

switch (tag) {
    case 1: { 
        // do something
        break;
    }
    case 2: {  
        if (/* condition */) {
            // Can I somehow jump to case 1?
        }
        break;
    }
}

Solution

  • No, not really. The closest thing you can get is a conditional fall-through.

    switch (tag) {
        case 2: {  
            // Do things that need to be done for case 2
    
            if(someCondition){
                // if the condition was met, we stop here   
                // and don't execute case 1!          
                break; 
            }
    
            // no break at the end, so we fall through to case 1
        }
        case 1: { 
            // do something
            break;
        }
    }
    

    But this can get very confusing very fast and is also quite limited, imo the better solution would be to write a function for each task and only use each case to call the appropriate function(s).


    And no, goto is a really bad idea and no, you shouldn't even think about using it ;)