Search code examples
c++cshort-circuiting

Replacing chained ifs with short-circuited operations


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.


Solution

  • 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.