Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using continue in a switch statement

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?

like image 950
Matt Joiner Avatar asked Jan 27 '10 12:01

Matt Joiner


People also ask

Can you use continue in a switch statement?

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.

Why continue Cannot be used in switch?

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..

Can continue be used in switch case in C?

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.

Can we use continue in switch in Javascript?

Continue may only refer to the loop. It can't be used inside the switch statement.


2 Answers

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(); 
like image 109
visitor Avatar answered Oct 23 '22 17:10

visitor


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 continue statement is related to break, but less often used; it causes the next iteration of the enclosing for, while, or do loop to begin. In the while and do, this means that the test part is executed immediately; in the for, control passes to the increment step.

The continue statement applies only to loops, not to a switch statement. A continue inside a switch inside a loop causes the next loop iteration.

I'm not sure about that for C++.

like image 37
Islam Elshahat Avatar answered Oct 23 '22 17:10

Islam Elshahat