c++ switch statement - jump between cases

Viewed 651

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

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

switch (tag) {
    case 1: { 
        // do something
        break;
    }
    case 2: {  
        if(){
            //can I somehow jump to case 1?
        }
        break;
    }
}
3 Answers

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 ;)

This is not the best way but will resolve your issue.

switch (tag) {
case 1: { 
    // do something
       case1:
               printf("hello");

    break;
}
case 2: {  
    if(){
        //you can use goto statement
        goto case1;
    }
    break;
}

}

As some pointed out, you can use goto. But it is not a good idea.

What you can do, and I also use this in my code sometimes, is to omit the break; statement and let several cases execute. If you decide to do so, keep a comment there, so future you (or your coworker) won't add the 'missing' break;.

Related