2

I have a loop that I want to unfold:

for(int i = 0; i < N; i++)
    do_stuff_for(i);

Unfolded:

for(int i = 0; i < N; i += CHUNK) {
    do_stuff_for(i + 0);
    do_stuff_for(i + 1);
    ...
    do_stuff_for(i + CHUNK-1);
}

But, I should make sure that I do not run out of the original N, like when N == 14 and CHUNK == 10. My question is: what is the best/fasters/standard/most elegant (you name it) way to do it?

One solution that comes is:

int i;
for(i = 0; i < (N % CHUNK); i++) 
    do_stuff_for(i);

for(i; i < N; i += CHUNK) {
    // unfolded, for the rest
}   

But maybe there is a better practice

Jakub M.
  • 32,471
  • 48
  • 110
  • 179

1 Answers1

7

You could use a switch-case.

It's called Duff's Device

Yochai Timmer
  • 48,127
  • 24
  • 147
  • 185