-
conditionals
Hi all,
I've got a question about conditionals which I couldn't find anything about it on previous posts...
I need to display 4 numbers when these are in range between min and max. I basically want to evaluate (true or false) in an "if" statement:
Code:
(min<=No1) && (max>+No1) && (min<=No2) && (max>+No2) &&(min<=No3) && (max>=No3) && (min<=No4) && (max>=No4)
I want to make this statement shorter but can you please explain why this is not working:?
Code:
(min<=No1<=max) && (min<=No2<=max) && (min<=No3<=max) && (min<=No4<=max)
Thanks!
-
min<=No1 evaluates to a boolean value, i.e., either 0 or 1.
Therefore, min <= No1 <= max is either:
0 <= max
or
1 <= max
This is clearly different from No1 <= max.
-
becuae means: (min <= No1) <= max - which doesn't do the same thing that you think it does, since the result of the "min<=No1" is either 0 or 1, which is likely outside the range of No1 .. max.
You could write a function or use a macro to do it:
Code:
int within(int x, int min, int max)
{
return (x >= min) && (x <= max);
}
or
Code:
#define WITHIN(x, min, max) (((x) >= (min)) && ((x) <= (max)))
--
Mats
-
this makes a lot of sense. Thank you very much!