Nested and extensible looping cycle in C

I am writing a C program where I control nested loops for, one inside the other, as follows:

for(i[0] = 0; i[0] < n[0]; i[0]++)
  for(i[1] = 0; i[1] < n[1]; i[1]++)
    for(i[2] = 0; i[2] < n[2]; i[2]++)
      {
       do_lot_of_work(i, n, 3);
      }

As you can see, the above code has three nested loops for. In my program, it takes into account 3 dimensions. However, I want to make my program extensible, which can take into account any number of measurements on the fly, as the user wishes; that is, for 4 dimensions, I want to have four nested loops forand do the work like do_lot_of_work(i,n,4). Similarly, for any number of measurements.

My question is: how to make the nesting of the loops described above forextensible?

Please note that to achieve the goal, I am ready to sacrifice internal loops for, but I want to keep the first loop forto make my program parallel with OpenMP.

+4
source share
2 answers

When the nesting level is unknown at compile time, use recursion to achieve the same effect:

void do_work(int i[], int n[], int pos, int size) {
    if (pos == size) {
        // All i-s are set - we are ready to roll
        do_lot_of_work(i, n, size);
    } else {
        for (i[pos] = 0 ; i[pos] < n[pos] ; i[pos]++) {
            do_work(i, n, pos+1, size);
        }
    }
}
+4
source

Use a recursive function.

void tons_of_work( int i[], int n[], int dims ) {
    loop_level( 0, i, n, dims );
}

void loop_level( int level, int i[], int n[], int dims ) {
    if ( level == dims ) {
        do_lot_of_work( i, n, dims );
    } else {
        int * ilevel = & i[ level ];
        for ( *ilevel = 0; *ilevel != n[ level ]; ++ *ilevel ) {
            loop_level( level + 1, i, n, dims );
        }
    }
}

loop_levelcalls itself to create nested loops until the innermost loop level is reached. Then he begins to do the "real" work.

+4
source

All Articles