Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 500
user666412 Avatar asked Mar 21 '13 21:03

user666412


2 Answers

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.

like image 141
meyumer Avatar answered Oct 06 '22 00:10

meyumer


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

like image 41
Loghorn Avatar answered Oct 06 '22 00:10

Loghorn