سؤال

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