最近我们找到了一个"好方法",通过使用continue来注释掉代码行:
for(int i=0; i<MAX_NUM; i++){
....
.... //--> about 30 lines of code
continue;
....//--> there is about 30 lines of code after continue
....
}
Run Code Online (Sandbox Code Playgroud)
我问问为什么前面的开发人员将continue关键字放在密集循环中.最有可能的是他/她认为放置"继续"关键字而不是删除所有不需要的代码更容易......
通过查看以下场景,它引发了另一个问题:
情景A:
for(int i=0; i<MAX_NUM; i++){
....
if(bFlag)
continue;
....//--> there is about 100 lines of code after continue
....
}
Run Code Online (Sandbox Code Playgroud)
情景B:
for(int i=0; i<MAX_NUM; i++){
....
if(!bFlag){
....//--> there is about 100 lines of code after continue
....
}
}
Run Code Online (Sandbox Code Playgroud)
你觉得哪个最好?为什么?break关键字怎么样?
sha*_*oth 23
continue在这种情况下使用可以大大减少嵌套,并且通常使代码更具可读性.
例如:
for(...) {
if( condition1 ) {
Object* pointer = getObject();
if( pointer != 0 ) {
ObjectProperty* property = pointer->GetProperty();
if( property != 0 ) {
///blahblahblah...
}
}
}
Run Code Online (Sandbox Code Playgroud)
变得公正
for(...) {
if( !condition1 ) {
continue;
}
Object* pointer = getObject();
if( pointer == 0 ) {
continue;
}
ObjectProperty* property = pointer->GetProperty();
if( property == 0 ) {
continue;
}
///blahblahblah...
}
Run Code Online (Sandbox Code Playgroud)
你看 - 代码变成线性而不是嵌套.
您可能还会发现这个密切相关的问题的答案很有帮助.
对于您的第一个问题,它可能是一种跳过代码而不会将其注释掉或删除它的方法.我不建议这样做.如果您不希望执行代码,请不要在其前面加上continue/break/return,因为这会在您/其他人查看代码时引起混淆,并且可能被视为错误.
至于你的第二个问题,它们基本上是相同的(取决于装配输出)性能,并且很大程度上取决于设计.这取决于您希望代码的读者将其"翻译"为英语的方式,就像大多数人在阅读代码时所做的那样.
所以,第一个例子可能是"Do blah,blah,blah.If(expression),继续下一次迭代." 虽然第二个可能读作"请等等,等等,等等.如果(表达),请做等等,等等,等等"
因此,使用if语句的继续可能会破坏其后面的代码的重要性.
在我看来,如果可以的话,我宁愿继续,因为它会减少嵌套.