views:

346

answers:

4

I want to jump from the middle of a switch statement, to the loop statement in the following code:

while (something = get_something())
{
    switch (something)
    {
    case A:
    case B:
        break;
    default:
        // get another something and try again
        continue;
    }
    // do something for a handled something
    do_something();
}

Is this a valid way to use continue? Are continue statements ignored by switch statements? I am technically trying to use this in C++, but I suspect it's probably the same as in C.

+5  A: 

Yes, it's OK - it's just like using it in an if statement. Of course, you can't use a break to break out of a loop from inside a switch.

anon
But `if` has no effect on the behaviour of `continue` or `break`. How do you mean it's alike?
Matt Joiner
@Matt I mean it will continue the loop in both cases.
anon
@Neil, okay, confusion averted.
Matt Joiner
I think it is still confusing.
Tim Schaeffer
+2  A: 

It's fine, the continue statement relates to the enclosing loop, and your code should be equivalent to (avoiding such jump statements):

while (something = get_something()) {
    if (something == A || something == B)
        do_something();
}

But if you expect break to exit the loop, as your comment suggest (it always tries again with another something, until it evaluates to false), you'll need a different structure.

For example:

do {
    something = get_something();
} while !(something == A || something == B));
do_something();
visitor
+1  A: 

While technically valid, all these jumps obscure control flow -- especially continue statement.

I would use such trick as a last resort, not first one.

How about

while (something = get_something())
{
    switch (something)
    {
    case A:
    case B:
        do_something();
    }        
}

I's shorter and perform its stuff in more clear way.

Alexander Poluektov
sorry for the confusion Alexander, the code is for demonstration only, i have good reason (i believe) for the actual structure in my code.
Matt Joiner
@Matt: That would probably mean an even more obfuscated structure... :)
visitor
@visitor, yes it does
Matt Joiner
A: 

It's syntactically correct and stylistically okay.

Good style requires every case: statement should end with one of the following:

 break;
 continue;
 return (x);
 case (x):
 default:
 //fallthrough

Anything else is suspected to be a mistake, just like if(a=4){...} Of course you need enclosing loop (while, for, do...while) for continue to work. It won't loop back to case() alone. But a construct like:

while(record = getNewRecord())
{
    switch(record.type)
    {
        case RECORD_TYPE_...;
            ...
        break;
        default: //unknown type
            continue; //skip processing this record altogether.
    }
    //...more processing...
}
SF.