|| operator combined with = operator

How come || operator works on the right side of = operator(not ==) but not on the left?

1
2
3
4
5
6
7
  case1
      int x=1, y=2, z=3;
      if(x = y || z) //worked

  case2
      int x=1,y=2,z=3;
      if (x || y = z) //didn't work 
Because of lazy evaluation of boolean statements.

x = y assignment will almost always evaluate to true (unless y is 0, I think).
For case2, x is 1, which evaluates to true, and since "true OR something" will always be true, it doesn't bother evaluating the right-hand expression.

Same goes for && (AND) logic when the left-hand side is false -- it won't bother evaluating the right-hand side.
Last edited on
No, it's because || has higher precedence than =. Note that this is = (the assignment operator), not == (equality test).

It's clearer if you add the parenthesis around the precedence. Your examples are the same as:
if (x = (y || z)) // assign result of y||z to x, then use x in if clause.

if ((x||y) = z) // can't assign z to "x||y"
Thank you for the anwsers, guys.
Yeah you're right @dhayden. Adding the parenthesis made it so much clearer. But could you please explain why we can't assign z to "x||y"?
Last edited on
Oh yeah, can't believe I didn't see that, dhayden is definitely correct.
(When you said "didn't work" I wrongly assumed that it still compiled.)
why we can't assign z to "x||y"?
Result of || will be either true or false

So you would have something like true = z (or 1 = z in C) which does not make any sense
(x || y = z)
this code has a separate comparison which is if (x = 1 or ( || ) y = z)
Thank you to everyone who helped.


why we can't assign z to "x||y"?


Sorry if i asked a silly question. I didn't fully understand Boolean Operations I confused || operator with plain English "or". I thought the result of "x||y" would be either x or y.
Lorence30, see my first post.

Nivekrulol, although you can't assign a value to a *or* b, you can assign a value to multiple variables in a single statement: a=b=3 assigns 3 to a and b. This works because = groups right to left (so it's a=(b=3)) and b=3 is not just a statement, it's an expression whose value is 3.
Topic archived. No new replies allowed.