5

Ran across some code that used this, which led me to wonder.

if(condition) foo = bar();

condition && (foo = bar());

Are these two segments of code equal to a compiler? If not, in what ways would they differ?

Anne Quinn
  • 12,609
  • 8
  • 54
  • 101
  • Such technique is used here : [Find maximum of three number in C without using conditional statement and ternary operator](http://stackoverflow.com/questions/7074010/find-maximum-of-three-number-in-c-without-using-conditional-statement-and-ternary) – Nawaz Sep 29 '11 at 09:47
  • Nawaz - Such an elegant solution for such a useless homework assignment. :P – Anne Quinn Sep 29 '11 at 09:52

6 Answers6

6

Due to operator precendence, the latter is interpreted as:

(condition && foo) = bar();

Additionally, there is a possibility of && being overloaded, which may result in pretty much anything.

So in short: they are not equal at all - at least in general case.

Xion
  • 22,400
  • 10
  • 55
  • 79
  • Ah, right you are! That was my mistake though, the parenthesis are present in the code I seen. Fixed the question – Anne Quinn Sep 29 '11 at 09:47
2

The first version is just a plain old statement.

The second version is an expression that will return the result of the entire expression. That probably allows some tricky one-line syntax that, as per usual, could potentially make code more readable but will more likely make it more complex and harder to parse quickly due to unfamiliarity.

IMO either use it everywhere consistently so that readers of your code get used to it, or don't use it at all.

Ayjay
  • 3,413
  • 15
  • 20
1

Unless condition && foo evaluates to an lvalue , condition && foo = bar(); is meaningless.

vivek
  • 4,951
  • 4
  • 25
  • 33
1

Unless && is overloaded for the combination of types of condition and foo they will have identical behavior - the latter will work this way:

bool result;
if( !condition ) {
     result = false;
} else {
     foo = bar();
     result = foo != 0;
}
and result gets ignored

that's usual short-circuiting - if the first component of && is false the second is not evaluated.

IMO the second variant is much less readable.

sharptooth
  • 167,383
  • 100
  • 513
  • 979
0

There is a compiler error: invalid l-value. To have same functionality you must use

conticion ? foo = bar( ) : <other accion>;
Tio Pepe
  • 3,071
  • 1
  • 17
  • 22
0

If && is not overloaded for neither condition nor foo:

condition && (foo = bar());

will be treated as

(condition.operator bool()) && (foo = bar());

if (condition.operator bool()) isn't true, (foo = bar()) won't be executed and vice versa.

GreenScape
  • 7,191
  • 2
  • 34
  • 64