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!
Aes*_*ete 38
不幸的是,continue与break在相同的PHP使用时switch的语句.
不要PHP破坏您的其他语言体验,并继续使用continue您需要的地方!
小智 7
PHP continue语句的文档清楚地表明了这一点:
注意:请注意,在PHP中,switch语句被认为是用于continue的循环结构.
您应该知道不同的语言给出相同的关键字略有不同的含义,并且不要假设PHP的continue行为与C++相同continue.
如果continue在PHP switch中有意义,它在C++中不起作用,请使用它.
如果continue在C++ switch中有意义,它在PHP中不起作用,请使用它.
| 归档时间: |
|
| 查看次数: |
18105 次 |
| 最近记录: |