12,634,982 members (28,597 online)
Rate this:
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 6:40am
zqliu359
Updated 21-Jan-13 7:02am
v3

Rate this:

## 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?
Rate this:

## 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 ();
```
Rate this:

## 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
Rate this:

## 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
Rate this:

## 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
 CPallini 175 Richard MacCutchan 165 OriginalGriff 88 Mika Wendelius 70 F-ES Sitecore 65
 OriginalGriff 2,412 ppolymorphe 1,321 Peter Leow 1,029 CPallini 806 John Simmons / outlaw programmer 770