How to define a range in an 'If' statement

I've just started playing with Arduino and can't find an answer to what I suspect is a very simple programming problem (my apologies, I am a real newbie).

My question, is there a way to create an IF statement that tests a range?

i.e: If (sensorValue>0 and less than 50), do this...

My problem is I don't know what operator to use to express that range 0 to 50 (if there is one).

I suspect this is a real newbie question - but I couldn't find an answer in the reference material.

Cheers

Peter

Oops, sorry I solved this myself using boolean ‘&&’.

If (sensorValue>0 && sensorValue<50)

Cheers

Peter

You’re absolutely correct. I’d advise adding a couple more sets of parentheses tho, just to make it absolutely clear what you want done.

If ((sensorValue>0) && (sensorValue<50))

Is sensorValue an unsigned int? If so you don’t need the first test in this example, but yes that’s how to do it.

You can also use || (OR), sometimes that’s appropriate.

Rob

Not everyone will agree with this, but to me the statement:

If (sensorValue>0 && sensorValue<50)

is easier to read (and debug) if it is written with spaces between the operators:

If (sensorValue > 0 && sensorValue < 50)

Also, you will find it easier to maintain and modify your code by getting rid of “magic numbers”. Try:

const int MINSENSORVALUE = 0;
const int MAXSENSORVALUE = 50;

If (sensorValue > MINSENSORVALUE && sensorValue < MAXSENSORVALUE )

Now if you buy new sensors that have different ranges, you change the two const definitions and everywhere those values are used in your code are automatically changed when you recompile the program. Personally, I prefer the old school way of doing the same thing:

#define  MINSENSORVALUE      0
#define  MAXSENSORVALUE     50

If (sensorValue > MINSENSORVALUE && sensorValue < MAXSENSORVALUE )

Whatever coding style you pick, use it consistently…it will pay off in the long run.

Not everyone will agree with this

I would.

Rob

I think anything that makes code clearer or easier to read is a good idea. I'm always surprised at how much I have to think when I'm reading through code that I've written but haven't looked at in a while. Suddenly, comments, spacing and the like seem like a much better idea!