If and or statement

Is this right with the parentheses

if ((data[2] > 0) || (data[0] > 0 && data[1] == 0)) 

Whatever operation is between parenthesis is evaluated first. Within parenthesis, operators with greater precedence evaluate first.

Your Boolean expression is sintactically correct, but I cannot say if it reflects what you want.

In this specific case (the inner) parenthesis are redundant because the and (&&) evaluates before the or (||) as && has greater precedence than ||.

so

if (data[2] > 0 || data[0] > 0 && data[1] == 0) 

if ether one is true
&& handled first

Can be written:

bool a = data[2] > 0;
bool b = data[0] > 0;
bool c = data[1] == 0;

if (a || (b && c)) // a is OR with the result of b AND c
  Serial.println("Make Pluto a Planet Again");

+1. I think I heard it's been moved to probation pending rehab.

a7

Looking for

if data[2] > 0
// if true then

if data[0] > 0 && data[1] == 0
// if true then

The whole expression will evaluate to true or false, answering "if (true)"

it should be:

if ((data[2] > 0) &&  ((data[0] > 0)   &&   (data[1] == 0))  )

Sorry this makes no sense
there is no OR in your code

There is no OR in your #6 message too.
I only translate your explanation to the logical expression.

1 Like

do you mean this:

if  (data[2] > 0) {
// do something if first condition match
}
else if ((data[0] > 0) && (data[1] == 0)) {
// do smth else, if first condition is false and the second and third are true
}

Thats it....
but the do something else would be the same as do something first condition
if one or the other is true..... do something

if (data[2] > 0 || (data[0] > 0 && data[1] == 0))

??

How then is this different from your very first message? - you already have code that matches this task.

What is the question then? Is something not working?

so what's the question?

i take it there is no difference between

if ((data[2] > 0) || (data[0] > 0 && data[1] == 0))
//or
if ((data[2] > 0) || data[0] > 0 && data[1] == 0)
//or
if (data[2] > 0 || data[0] > 0 && data[1] == 0)

I always enclose all expressions:

if ( (data[2] > 0) || ((data[0] > 0) && (data[1] == 0)))

There is no such thing as too many parentheses.
It's better to add extra parentheses than to spend hours or days trying to figure out why the code doesn't work.

Writing that:

are you sure that in a year you will remember that the operator "OR" here refers to the two conditions on the right, and not just the middle one?

Yes
but getting old :smile:
Thank You

Post 4.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.