原帖子:http://top.jobbole.com/4960/
在Stack Overflow
上的一个挺有趣的问题,详细整理问题和部分巧妙的回答如下。
假设我刻意写了一段代码:
boolconditionA = executeStepA();
if(conditionA){
boolconditionB = executeStepB();
if(conditionB){
boolconditionC = executeStepC();
if(conditionC){
...
}
}
}
executeThisFunctionInAnyCase();
从代码可以看出,executeStepX
函数只有在前面的条件为真时才执行。executeThisFunctionInAnyCase
无论如何(异常除外)都会在最后执行。现在我有一个很基础的问题: 在C/C++当中,有没有什么方法可以避免这种冗长的 if
条件语句嵌套?
我知道如果不要求最后执行 executeThisFunctionInAnyCase 的话,代码可以重构成这样:
boolconditionA = executeStepA();
if(!conditionA) return;
boolconditionB = executeStepB();
if(!conditionB) return;
boolconditionC = executeStepC();
if(!conditionC) return;
但是,如果最后调用executeThisFunctionInAnyCase
是必须的,我该如何重构if条件嵌套呢?
部分巧妙的回答请看评论。欢迎你也在评论中分享观点~
神解答:
-
do{ if(!executeStepA()) break; if(!executeStepB()) break; if(!executeStepC()) break; }while(0); executeThisFunctionInAnyCase();
-
7 楼
使用 && 的话,其实 if 可以不用
12executeStepA() && executeStepB() && executeStepC();
executeThisFunctionInAnyCase();
解释:
&&相当一个开关语句,就是说如果&&前面值为false那么他就不继续执行后面的表达式;而&不管前面的值为什么,总是执行其后面的语句。