Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do logical operators affect each other in a if statement?

I have 4 statements, I only want to check statement 2-4 if statement 1 is true the following is the pseudo code of what I am trying to achieve

if (statement 1) {
  if (statement 2 or statement 3 or statement 4){
    do something()
  }
}

I was wondering whether the following code will do the same

if(s1 && s2 || s3 || s4) {
  doSomething();
}

or if I have to do it like

if (s1) {
  if (s2 || s3 || s4) {
     doSomething();
  }
}
like image 207
Ariel Hurdle Avatar asked Aug 21 '19 13:08

Ariel Hurdle


2 Answers

Due to operator precedence

if(s1 && s2 || s3 || s4) 

is the same as

if((s1 && s2) || s3 || s4) 

since && has a higher precedence than ||. What you want is

if(s1 && (s2 || s3 || s4)) 

which will only be true if s1 is true and any of s2, s3, and s4 are true.

You are also guaranteed to have short circuiting on && as long as that is a built in operator and that means that if s1 is false, s2, s3, and s4 will not be evaluated. This also happens wth || for built in operators and as soon as you hit a true expression the rest won't be evaluated as true or anything is true.

like image 157
NathanOliver Avatar answered Sep 28 '22 16:09

NathanOliver


In C++ the logical operators && and || are short-circuiting - this means that the left operand of the operator is going to be evaluated first, and if the result won't be affected by doing further evaluations then it'll stop there. For example, x() && y() will indeed only evaluate y() if x() was true, and x() || y() will only evaluate y() if x() was false.

As a recommendation, you should take care to put parentheses around things to make it more clear which order of operations you intended though:

s1 && (s2 || s3 || s4)

rather than

s1 && s2 || s3 || s4
like image 44
Cubic Avatar answered Sep 28 '22 17:09

Cubic