Neater Way Of Testing If A Variable Is Between Two Constants In If ...

neater way of testing if a variable is between two constants in if statement Projects Programming June 3, 2015, 10:18pm 1

Just debugging my program, i've written this;

if (0 < columnNumber < 3) {       sectorNumber = 0;           }

Which is obviously wrong as it doesn't work. It made sense in my head when i wrote it but the processor is having none of it.

My fix is this;

if (columnNumber > 0 && columnNumber < 3) {       sectorNumber = 0;           }

My question is; is there a neater way to write it, thats closer to the first one?

Thanks in advance, Ben.

June 3, 2015, 10:24pm 2

But the second one is neat ! That is normal 'c' programming.

There is no "check if in between" condition in the 'c' language. Comparing two values is normal, and you have to do that twice when you want to check if it is in between two values. That's how it is, and it's not so bad at all, because it is very straightforward for a programmer and a compiler.

June 3, 2015, 10:36pm 3

Thanks, i was just sure i had seen something similar to my original statement before.

June 3, 2015, 10:40pm 4

Take the following statement

if ( x > 5){   //Do stuff }

suppose x = 5.

is the stuff done or not?

June 3, 2015, 10:49pm 5

It is possible to compare integers, but also float numbers.

int x = 5; if ( x > 5 ) {   // Do stuff }

The stuff is not done. Only if 'x' is really greater than 5. So 'x' must be 6,7,8,9,10, and so on.

That is why the '>=' often is used (greater or equal than).

With float numbers it is like this:

float z = 5.001; if( z > 5.0) {   // Do stuff }

Here the 5.001 is greater than 5.0, so the stuff is executed.

June 4, 2015, 4:46pm 6

comparison can visually show it is between or outside

if (0 <= x && x <= 3) // between if (y < 0 || 10 < y) // outside

or you create a macro (like min, max etc) but be aware all culprits of macros apply...

#define between(x, a, b)  (((a) <= (x)) && ((x) <= (b))) #define outside(x, a, b)  (((x) < (a)) || ((b) < (x)))

Note I interpreted between as between inclusive and outside as outside exclusive. This makes the two macros complementary.

June 4, 2015, 7:52pm 7

Thanks for the responses, very informative

Topic Replies Views Activity
Comparison operator range Programming 9 802 October 23, 2022
How to define a range in an 'If' statement Programming 7 13450 May 5, 2021
Stato compreso tra Software 2 2102 May 7, 2021
How to use if between two values? Programming 7 53612 May 5, 2021
compare statement Programming 9 799 May 5, 2021
Unfortunately, your browser is unsupported. Please switch to a supported browser to view rich content, log in and reply.

Tag » Arduino If Statement Between Two Values