John Gkikas John Gkikas - 20 days ago 8
C Question

multiple if conditions optimisation

I am building a simple C project (for arduino) and I have come across this question.It's not actually that language specific, it's more of an algorithm optimisation thing.

So, I need to check a value of X against a sensor reading.

If X <5 ...
else if x<10...
else if x<15...
else if x<20...


Then in each clause I have the same for loop,but the iterations change depending on the value of X.

In a general sense, how can these if conditions be replaced by something unified?I remember these "gradation" or "leveling" problems in highschool, but we still used if clauses.

Answer

Then in each clause I have the same for loop,but the iterations change depending on the value of X.

I'd set a variable to the number of iterations, then put the for loop after the if/else sequence.

int loops;
if (X < 5) {
    loops = /*whatever*/;
} else if (X < 10) {
    loops = /*whatever*/;
} else if (X < 15) {
    loops = /*whatever*/;
// ...and so on...
} else {
    loops = /*whatever for the catch-all case*/;
}
for (int i = 0; i < loops; ++i) {
    // ...
}

If you're trying to avoid the if/else, if there are only a small number of possible sensor values, you could use a switch instead, which in some languages is compiled to a jump table and so fairly efficient.

If you want to have the ranges held as data rather than in an if/else sequence, you could use an array of values:

int[][] values = {
    {5, 500},
    {10, 700},
    {15, 800},
    {20, 1200},
    {0, 1500}  // 0 is a flag value
};

(There I'm using an array of int[], but it could be a nice clean class instance instead.)

Then loop through the array looking for the first entry where X < entry[0] is true (or where entry[0] is 0, to flag the last entry).

int loops = 0; // 0 will never be used, but the compiler doesn't know that
for (int[] entry : values) {
    if (entry[0] == 0 || X < entry[0]) {
        loops = entry[1];
        break;
    }
}

...followed by the for loop using loops.

Comments