Jakub M.
Jakub M.

Reputation: 33827

C++ loop unfolding, bounds

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

Upvotes: 2

Views: 1474

Answers (1)

Yochai Timmer
Yochai Timmer

Reputation: 49251

You could use a switch-case.

It's called Duff's Device

Upvotes: 7

Related Questions