Reputation: 78
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();
}
}
Upvotes: 5
Views: 152
Reputation: 1014
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.
Upvotes: 1
Reputation: 180955
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.
Upvotes: 8
Reputation: 15693
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
Upvotes: 1