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? Do C and C++ differ on their behaviour here?
We can not use a continue with the switch statement. The break statement terminates the whole loop early. The continue statement brings the next iteration early. It stops the execution of the loop.
Falling through is the standard behavior for a switch statement and so, consequently, using continue in a switch statement does not make sense. The continue statement is only used in for/while/do..
The continue statement is not used with the switch statement, but it can be used within the while loop, do-while loop, or for-loop.
Continue may only refer to the loop. It can't be used inside the switch statement.
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(); 
                        Yes, continue will be ignored by the switch statement and will go to the condition of the loop to be tested. I'd like to share this extract from The C Programming Language reference by Ritchie:
The
continuestatement is related tobreak, but less often used; it causes the next iteration of the enclosingfor,while, ordoloop to begin. In thewhileanddo, this means that the test part is executed immediately; in thefor, control passes to the increment step.The continue statement applies only to loops, not to a
switchstatement. Acontinueinside aswitchinside a loop causes the next loop iteration.
I'm not sure about that for C++.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With