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

2024-04-12

我注意到你确实可以使用continueswitch 语句中的关键字,但在 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
*/

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 语句的循环的下一次迭代。

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!

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

我应该在 switch 语句中使用 continue 吗? 的相关文章

随机推荐