Comparison operator range

Will this work? So that the if statement will become true when the sensor is in between 49 and 99?

Example:

If( 49 < sensor < 99)
{
do something here
}

No. That will always be true. You need two test clauses linked with a logical and (&&).

1 Like

No, use this idiom:

If (49 < sensor and sensor < 99)
{
  //do something here
}

'and' is the modern C++ alternative to &&, ditto 'or' for || and 'not' for !

I think you are thinking of Python syntax for range comparisons, which is different.
In C and C++ "a < b < c" parses as "(a < b) < c", which compares a boolean to a number, not what you were expecting.

2 Likes

Will this be correct?

if ((Sensor > 49 && Sensor < 99) && Flag == true)
{
  Do something
}

Yes, but usually when testing booleans, you would drop the == true.

Oh sorry I am actually creating a push notification when the sensor is triggered so i added a flag in the variables but it should be "false" sorry

What would be the difference between this two? And which would be better to use?

if ((Sensor > 49 && Sensor < 99) && Flag == false)
{
  //Do something here
}

////////////


if ((Sensor > 49 || Sensor < 99) && Flag == false)
{
  //Do something here
}

The second is nonsense - its a tautology, Sensor must always be either less than 99 or more than 49.

Why not use

1 Like

I'll try this and update you later with the results :slight_smile:

Thanks it works like a charm!

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