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

标签 php c++ language-agnostic switch-statement

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

如果 PHP 失败了,谁知道还有多少其他语言也失败了?如果我经常在语言之间切换,如果代码的行为不像我预期的那样,这可能是个问题。

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

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

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

最佳答案

尝试使用 continue 2 继续围绕 switch 语句的循环的下一次迭代。

编辑:

    $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;
    }

//这将打印: sleep ... sleep ... sleep ... 世界你好!

关于php - 我应该在 switch 语句中使用 continue 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12349826/

相关文章:

language-agnostic - 高尔夫球代码:将乘法表输出到控制台

php - 在没有 Join 的情况下,在 3 个表中查找带有 field_in_set 的标签

java - 严格的服务器端处理(无网络浏览器交互): is Java or PHP better for this scenario?

javascript - 在 if/else 语句返回时隐藏 DIV

c++ - 哪里有关于使用 C++ 源代码创建 R 包的好教程?

c++:根据预定义的元素索引选择 std::vector 的子集

data-structures - 我可以在 1GB 内存中创建多少个整数?

php - Laravel如何在错误填写表单字段时引发单个错误

c++ - cocos2dx 中的重写函数

vb.net - 直接访问数据成员是不好的做法吗?