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 traditional

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

or

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

I was thinking of writing an expression as a short-circuited assessment.

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

But I have never seen this test run this way in C / C ++ code. Are there any problems with this approach that I am missing?

Thank.

+5
source share
2 answers

The code you wrote is valid. d()will be evaluated only if other Boolean functions are returned false.

, .

+3

, , .

+2

All Articles