Alex Rivera | Logout

Should I ever use continue inside a switch statement?

Asked 2012-09-10T10:30:22.537
55

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
*/
Edit
Report

2 Answers

8

The documentation for the PHP continue statement makes this clear:

Note: Note that in PHP the switch statement is considered a looping structure for the purposes of continue.

You should know that different languages give the same keywords subtly different meanings, and not assume that PHP continue behaves the same as C++ continue.

If continue makes sense in a PHP switch where it wouldn't work in C++, do use it.

If continue makes sense in a C++ switch where it wouldn't work in PHP, do use it.

answered 2012-09-10T10:36:57.923
0

In C and C++, the switch statement is only a fancy combination of if/else if and labels/goto, so using continue inside switch is okay. But as you noticed it doesn't do what you expect it to in other languages that are similar to C or C++. That's because they are only similar when it comes to syntax, for semantic rules they are very different beasts. So a thing that works in one language will most definitely not work in another even if the languages look similar.

answered 2012-09-10T10:37:50.220

Your Answer