Code: Select all

`int v[k];`

for (int i = 0; i < n; ++i) {

getData(i, v, k);

if (needResultA) { calculateA(v, k); }

if (needResultB) { calculateB(v, k); }

}

Of course putting the conditional check inside the loop is slow, but if I pull it out then I end up with something like this:

Code: Select all

`int v[k];`

if (needResultA && needResultB) {

for (int i = 0; i < n; ++i) {

getData(i, v, k);

calculateA(v, k);

calculateB(v, k);

}

} else if (needResultA) {

for (int i = 0; i < n; ++i) {

getData(i, v, k);

calculateA(v, k);

}

} else if (needResultB) {

for (int i = 0; i < n; ++i) {

getData(i, v, k);

calculateB(v, k);

}

}

That, obviously, has a lot of repetition—and if there were more than 2 calculations, any arbitrary combination of which might be needed, it would require stupid amounts of code duplication. Making separate functions for each of the 2

^{|calculations|}−1 possibilities would appear to have the same problem.

So what’s the right way to accomplish this?