cnested-loopsn-dimensional

In C, how to write a N-dimensional nested for loop where N is variable


I need to write the statement:

for ( int i1 = i1_min; i1 < width; ++i1 )
    for ( int i2 = i2_min; i2 < i2_max; ++i2 )
        for ( int i3 = i3_min; i3 < i3_max; ++i3 )
            ...
                for ( int iN = iN_min; iN < iN_max; ++iN )

How to do it?


Solution

  • You could write a recursive function loopn() to do this:

    void loopn_recurse (int *min, int *max, int *counters, size_t N, size_t n, void (*func)(int*, size_t)) {
      for (int i = min[n]; i < max[n]; ++i) {
        counters[n] = i;
    
        if (N - n > 1) {
          loopn_recurse(min, max, counters, N, n + 1, func);
        } else {
          // innermost algorithm
          func(counters, N);
        }
      }
    }
    
    void loopn (int *min, int *max, int *counters, size_t N, void (*func)(int*, size_t)) {
      assert(N > 0);
      loopn_recurse(min, max, counters, N, 0, func);
    }
    
    // example usage
    
    void test (int *counters, size_t N) {
      for (size_t j = 0; j < N; ++j) {
        printf("%d ", counters[j]);
      }
    
      putchar('\n');
    }
    
    loopn((int[]){ 1, 2, 3, 4, 5 }, (int[]){ 2, 4, 6, 8, 10 }, (int[5]){}, 5, test);
    

    Try it online!