Sha*_*awk 3 c break while-loop
举个例子:
function()
{
calculation1();
while(1)
{
if (test1() == FAIL) { break; }
calculation2();
if (test2() == FAIL) { break; }
calculation3();
if (test3() == FAIL) { break; }
calculation4();
break;
}
final_calculation();
return;
}
Run Code Online (Sandbox Code Playgroud)
每个测试取决于从它之前的所有计算中获得的结果.但是,如果测试失败,则应跳过其余计算.
另一种方法是使用一系列嵌套的if()语句:
function()
{
calculation1();
if (test1() == SUCCESS)
{
calculation2();
if (test2() == SUCCESS)
{
calculation3();
if (test3() == SUCCESS)
{
calculation4();
}
}
}
final_calculation();
return;
}
Run Code Online (Sandbox Code Playgroud)
然而,后一种方法开始看起来非常混乱,除了像上面这样的高度抽象的例子.我相信前一种方法可以更好地扩展到更长,更复杂的代码.有没有理由不采用第一种方法?
我对这种技术没有任何问题,并经常使用它.
但是,我通常将其格式化为:
bool success = false; // Pessimistically assume we will fail
do
{
calculation1();
if (test1() == FAIL)
{
break;
}
calculation2();
if (test2() == FAIL)
{
break;
}
calculation3();
if (test3() == FAIL)
{
break;
}
calculation4();
success = true; // Note the success!
} while(false);
// TODO: Check the success-variable to know if we failed early, or went all the way through.
final_calculation();
return;
}
Run Code Online (Sandbox Code Playgroud)
(有时我的同事不喜欢while(false)有条件的循环)
| 归档时间: |
|
| 查看次数: |
105 次 |
| 最近记录: |