[Solved] Can you write if ( (x && y) || y || z) { do this;}? [closed]


It is valid syntax provided all the identifiers involved are bool identifiers, meaning a local variable, a parameter, a constant, field or a property that holds a bool value. If they’re not, then no, that is not legal syntax.

I am also only referring to this part:

if ( (x && y) || y || z) { do this;}
^----------------------^

The last part: { do this; } is not legal syntax but I understood your question to not be about that part.

Specifically, your whole statement says this:

  • Either x && y has to be true
  • Or y has to be true
  • Or z has to be true

If any of those holds, then “do this”, whatever that may be.

Now, let’s analyze your expression a little further.

Since y stands alone, there seems to be little point in involving x.

Let’s look at this expression: (x && y) || y and look at the possible values of x and y and the result:

   x   |   y   |   result  |  why?
---------------------------------------------
 false | false | false     | because neither x nor y is true
 false | true  | true      | because y is true: ... ? || y
 true  | false | false     | because y has to be true either way
 true  | true  | true      | because y is true: ... ? || y

Basically, you can remove x altogether, it has no bearing on the results (see my extra comment below though).

Your final statement could thus be this:

if (y || z) { do this; }

Now, having said all of that, here’s one additional thing. I am also assuming that x, y and z are placeholders for something else. What if x was a method? Would it matter then?

Yes, because to know the result of x() the method would have to be called. If calling the method has side-effects beyond just returning true or false then you may very well not want to simply remove it. The final result of the expression is not going to depend on the value of x, but the side-effects might be warranted either way. Questionable design perhaps, but that’s hard to tell without something more specific.

16

solved Can you write if ( (x && y) || y || z) { do this;}? [closed]