Function with multiple if or with a "big" return?

I would like to know if one of this two solution is better than the other :

Version 1:

bool myFunction()
{
    if (A)
        return false;
    if (B)
        return false;
    if (C)
        return false;
    if (D)
        return false;

    return true;
}

Version 2 :

bool myFunction()
{
    return (!A && !B && !C && !D);
}

I guessed that version 2 may be a bit less efficient as we may have to calculate the whole boolean expression to know if it's true or false. In the first version, if A is false, it returns false, without calculating B, C or D. But I find second version much more readable.

So what is the best way to do that ?

Thank you.

Jon Skeet
people
quotationmark

In the first version, if A is false, it returns false, without calculating B, C or D.

That's true for the second version as well. The && operator is short-circuiting - if the first operand is false, it won't evaluate the second operand.

However, I'd either remove the brackets from the second version:

return !A && !B && !C && !D;

or invert it to:

return !(A || B || C || D);

... depending on which you find simpler to read. I personally prefer to have as few negations as possible. (|| is also short-circuiting, so they're equivalent in efficiency.)

Don't avoid multiple return statements on principle, mind you - there are plenty of times where using multiple return statements gives more readable code. Aim for the most readable code you can, and only worry about efficiency when you've proved that the most readable approach doesn't perform as well as you need it to. In this case, the approaches are equally efficient, so that's not a concern anyway.

people

See more on this question at Stackoverflow