13,553,357 members
See more:
`f1()`, `f2()`, `f3()` is a function of type `bool`, which of the following style is better?
```A. if (f1 () && f2 () && f3 ()) do ();
B. if (f1 ())
if (f2 ())
if (f3 ())
do ();
```

If three function execution time is longer, is B method is better? Or they are just the same effect in different write way?
Posted 21-Jan-13 5:40am
Updated 21-Jan-13 6:02am
v3

## Solution 1

They should be about the same. I prefer A; it's more polished. Any fool can do B.
v2
rizwan muhammed khan gouri 22-Jan-13 8:58am

Why you give Answare For this time besting type of quertion...........
PIEBALDconsult 22-Jan-13 9:01am

Ummm... what?

## Solution 2

It actually doesn't matter from a run-time point of view. In other words, A and B will run equally fast. For readability purposes, however, I would always prefer A. or better yet

```if (f1() && f2() && f3())
doSomething ();```

## Solution 3

I'd prefer A. If `(f1 () && f2 () && f3 ()) do ();` because it is much more clearer and easier to understand.

You are using `&& `which is a short circuit operator.
If the first condition fails the second won't execute so there will be no difference in execution time in either case.
v3

## Solution 4

You left out a 3rd variant:
```bool hasSomethingToDo = f1() && f2() && f3();
if (hasSomethingToDo)
{
DoSomething();
}```

and a 4th variant:
```bool hasSomethingToDo = f1()
&& f2()
&& f3();
if (hasSomethingToDo)
{
DoSomething();
}```

Usually, your functions are not that short as you show above. So, if the function calls are a bit more text, than I go for the 4th variant.

With one or two function calls, I go for the 1st variant. The second variant is the one I avoid as much as possible.

BTW: Execution time shoud not differ in a relevant manner - it's a question of style (if it's relevant, measure it!).

Cheers
Andi

## Solution 5

Any C/C++ compiler nowadays will treat both the same way and generate either the same code or almost the same code.

A point perhaps more important than performance for this one-liner is maintainability. In most cases, 'A' is the better choice - if the logical tests are truly function names or very short expressions.

But this is a razor-thin advantage. If the tests get more complicated, it might be better to break out into multiple 'if' statements for readability purposes. ... and if you ever need to insert an 'else' clause, then 'B' for at least that part of it is better. Don't repeat boolean tests to avoid 'B' logic.

Also never do

```if(x == true) {...}
if(x == false) {...}```

or you'll never get near my code base...

Top Experts
Last 24hrsThis month
 OriginalGriff 264 Maciej Los 175 ppolymorphe 120 Richard MacCutchan 90 Richard Deeming 90
 OriginalGriff 5,309 ppolymorphe 2,372 Richard MacCutchan 2,185 Wendelius 1,890 Maciej Los 1,775