我应该在switch语句中使用continue吗?

Roo*_*kie 36 php c++ language-agnostic switch-statement

我注意到你确实可以continue在switch语句中使用关键字,但是在PHP上它并没有达到我的预期.

如果它失败了PHP,谁知道它失败了多少其他语言呢?如果我在语言之间切换很多,如果代码的行为不像我期望的那样,那么这可能是一个问题.

我应该避免continue在switch语句中使用吗?

PHP(5.2.17)失败:

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
*/
Run Code Online (Sandbox Code Playgroud)

C++似乎按预期工作(跳转到for循环结束):

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
*/
Run Code Online (Sandbox Code Playgroud)

Lia*_*iam 69

尝试使用continue 2继续循环语句周围的循环的下一次迭代.

编辑:

    $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;
    }
Run Code Online (Sandbox Code Playgroud)

//This will print: Sleeping... Sleeping... Sleeping... Hello World!

  • 我刚刚遇到了一个用例,其中我有一个带有开关的 for 循环。很有用!PHP break n / continue n 语法在很多场景下为我节省了很多精力。如果您详细说明这个答案,我认为这应该是公认的答案。 (2认同)
  • 使用PHP已有7年了,我仍在学习PHP的基础知识!难以置信的!非常感谢! (2认同)

Aes*_*ete 38

不幸的是,continuebreak在相同的PHP使用时switch的语句.

不要PHP破坏您的其他语言体验,并继续使用continue您需要的地方!

  • @Rookie [因为这就是PHP滚动的方式:就像方形滚轮一样. - *Ignacio Vazquez-Abrams*](http://stackoverflow.com/questions/12151997/why-does-1234-1234-test-evaluate-to-true):) (4认同)
  • @Rookie在C++中,`continue {和`break`在`do {...} while(0)`循环中是相同的,但它们在其他上下文中是不同的.在PHP中,`continue`和`break`在`switch`语句中是相同的,但它们在其他上下文中是不同的. (3认同)

小智 7

PHP continue语句的文档清楚地表明了这一点:

注意:请注意,在PHP中,switch语句被认为是用于continue的循环结构.

您应该知道不同的语言给出相同的关键字略有不同的含义,并且不要假设PHP的continue行为与C++相同continue.

如果continue在PHP switch中有意义,它在C++中不起作用,请使用它.

如果continue在C++ switch中有意义,它在PHP中不起作用,请使用它.