5

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();
  }
}
NathanOliver
  • 171,901
  • 28
  • 288
  • 402
Ariel Hurdle
  • 68
  • 1
  • 13
  • 3
    Be careful with operator precedence. `&&` has higher precedence than `||`, so you want `if(s1 && (s2 || s3 || s4))`. – Blaze Aug 21 '19 at 13:36
  • `s1 && s2 || s3 || s4`, due to rules of operator precedence, is equivalent to `(s1 && s2) || s3 || s4`, not to `s1 && (s2 || s3 || s4)`. Your second lot of code tests the latter. – Peter Aug 21 '19 at 13:39

3 Answers3

8

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.

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
1

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
Cubic
  • 14,902
  • 5
  • 47
  • 92
1

You need to put parenthesis on your || statements. So:

if(s1 && (s2 || s3 || s4)) { // << note the parenthesis
  doSomething();
}

is equivalent with

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

This works because of Short-circuit evaluation. Basically if s1 is false, the parenthesis won't be evaluated. You can read about it here.

N Alex
  • 1,014
  • 2
  • 18
  • 29