I noticed you can indeed use the continue
keyword in a switch statement, but on PHP it doesn't do what I expected.
If it fails with PHP, who knows how many other languages it fails too? If I switch between languages a lot, this can be a problem if the code doesn't behave like I expect it to behave.
Should I just avoid using continue
in a switch statement then?
PHP (5.2.17) fails:
for($p = 0; $p < 8; $p++){ switch($p){ case 5: print"($p)"; continue; print"*"; // just for testing... break; case 6: print"($p)"; continue; print"*"; break; } print"$p\r\n"; } /* Output: 0 1 2 3 4 (5)5 (6)6 7 */
C++ seems to work as expected (jumps to end of for loop):
for(int p = 0; p < 8; p++){ switch(p){ case 5: cout << "(" << p << ")"; continue; cout << "*"; // just for testing... break; case 6: cout << "(" << p << ")"; continue; cout << "*"; break; } cout << p << "\r\n"; } /* Output: 0 1 2 3 4 (5)(6)7 */
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.
The continue statement isn't used with the switch statement, but it can be used in a while, do-while, or for loop. The break statement ends the loop prematurely. The continue statement signals the start of the following iteration. It halts the loop's execution.
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.
The value of the expressions in a switch-case statement must be an ordinal type i.e. integer, char, short, long, etc. Float and double are not allowed. The case statements and the default statement can occur in any order in the switch statement.
Try using continue 2
to continue to the next iteration of the loop surrounding the switch statement.
EDIT:
$foo = 'Hello'; for ($p = 0; $p < 8; $p++) { switch($p) { case 3: if ($foo === 'Hello') { echo $foo; break; } else { continue 2; } default: echo "Sleeping...<br>"; continue 2; } echo "World!"; break; }
//This will print: Sleeping... Sleeping... Sleeping... Hello World!
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