如果变量为True / False,则更好地执行

问题描述 投票:-2回答:1

我可以改善此代码设计吗?

如果变量为True / False,我正在寻找更好的代码来执行。

void test(int a) {
    // ...

    if (a) {
        if (testCall() > 0) {
            // ...
        }
    }

    // ...
}

test(0); // testCall() hasn't been executed
test(1); // testCall() has been executed

非常感谢!

c++ optimization
1个回答
-3
投票

如果要避免嵌套if,则可以利用所谓的惰性求值:

void test(int a) {
    // ...
    if (a && testCall() > 0) {
        // ...
    }
    // ...
}

如果从左到右求值;看到有&&,如果a的值为false,则很明显整个条件为false,因此程序不会前进到下一条语句,而是直接跳转到[ C0]子句(如果有)。这样,else将不会执行。

© www.soinside.com 2019 - 2024. All rights reserved.