#&& || Logical operators question
1 messages · Page 1 of 1 (latest)
So if I have
if(a==1 && b==1 || c==1)
All it takes is for c==1 for the thing to happen?
Now that I've typed the question out in simple terms, it seems a bit obvious.
Could I separate them like this?
[if(a==1 && b==1 || c==1 && d==1):the thing]
Or would the check d==1 before c==1?
Without ()'s is goes from left to right. afaik, it has the same priority. If you wish to group them, then use ()'s but you're limited to nesting only 1 pair at a time. [if((a==1 && b==1) || (c==1 && d==1)): "true"]
Even if you know that expressions are evaluated in a particular order, odds are the next person who looks at your code won't know that (including you, six months from now!). It's always better/safer to use parens as AM describes.
Thanks both. I hadn't even considered using ()s in the if().
The line about it in the wiki makes sense now.
&& has higher priority.
[r: 1 || 0 && 0] is 1
If they had the same priority and the only relevance was left to right, then this would be 0. [r: (1 || 0) && 0] is 0.
[r: 0 && 0 || 1] is 1
If || had higher priority, then this would be 0. [r: 0 && (0 || 1)] is 0.
Edit:
Like Azhrei already wrote, better use ()'s though if the check is not completely obvious, to make sure everyone involved understands what the code does.
@old frigate ^
Oh man. You can get up to all sorts of logical shenanigans.
I just did:
[if( (A && B) && (C || D) ):theThing]
It was awesome.
btw that's just A && B && (C || D). It's a bit like (A * B) * C is just A * B * C and you don't strictly need the parentheses.