This is a very trivial problem: There are four boolean functions: a(), b(), c() and d(). I want to keep calling them in order until the first one returns true. instead of doing the traditional

if(!a()) {
    if(!b()) {
        if(!c()) {
            d();
        }
    }
}

or

if(!a() && !b() && !c()) d();

I thought about writing the expression as a short-circuited evaluation.

(a() || b() || c() || d());

But I've never seen this test being done this way in a C/C++ code. Is there any problem with this approach that I'm missing?

Thanks.

有帮助吗?

解决方案

The code you have written is valid. d() will only be evaluated if other boolean functions return false.

However the short-circuited evaluation is less readable, and error prone from a maintenance point of view, because a reader might not get understand it trivially.

其他提示

They are equivalent, but the short-circuited evaluation solution could be less readable, especially if function names are long or accepts parameters.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top