我可以改善此代码设计吗?
如果变量为True / False,我正在寻找更好的代码来执行。
void test(int a) {
// ...
if (a) {
if (testCall() > 0) {
// ...
}
}
// ...
}
test(0); // testCall() hasn't been executed
test(1); // testCall() has been executed
非常感谢!
如果要避免嵌套if,则可以利用所谓的惰性求值:
void test(int a) {
// ...
if (a && testCall() > 0) {
// ...
}
// ...
}
如果从左到右求值;看到有&&,如果a
的值为false
,则很明显整个条件为false
,因此程序不会前进到下一条语句,而是直接跳转到[ C0]子句(如果有)。这样,else
将不会执行。