Hi, I have the four following variables, and the values of these variables need to be within a set a threshold of the optimal value. The only way I can think of at the moment to validate them is with the following code. If anyone could suggest an alternative way that would be great:
I could put the values in an array, and go through each one. However, this is more time consuming. Additionally, the number of variables required is always going to be 4, so there is not really a maintainability advantage in using an array.
const int OPTIMAL_VAL = 5;
const int THRESHOLD_VAL = 1;
int iA = 4, iB = 5, iC = 5, iD = 6;
if((OPTIMAL_VAL - THRESHOLD_VAL >= iA && iA <= OPTIMAL_VAL + THRESHOLD_VAL) &&
(OPTIMAL_VAL - THRESHOLD_VAL >= iB && iB <= OPTIMAL_VAL + THRESHOLD_VAL) &&
(OPTIMAL_VAL - THRESHOLD_VAL >= iC && iC <= OPTIMAL_VAL + THRESHOLD_VAL) &&
(OPTIMAL_VAL - THRESHOLD_VAL >= iD && iD <= OPTIMAL_VAL + THRESHOLD_VAL))
a function for each threshold check might be prettier, but w.e works
It should be
OPTIMAL_VAL - THRESHOLD_VAL <= iA && iA <= OPTIMAL_VAL + THRESHOLD_VAL
And since OPTIMAL_VAL - THRESHOLD_VAL and OPTIMAL_VAL + THRESHOLD_VAL don't change, calculate them once.
OPTIMAL_VAL - THRESHOLD_VAL >= iA && iA <= OPTIMAL_VAL + THRESHOLD_VAL
the compiler will perform such trivial optimizations itself, no need to worry about that
Sure, but it looks less cluttered ;)
i'm all for that. recommend using a two letter macro, such as OT to replace them as well.
(in all seriousness :cool: )
Hi all, Thanks for your replies. I noticed the problem about coditions being the wrong way. Thanks for the suggestions, I will implement them.