Nested for-loops via preprocessor

Hello dear users,

I am currently working on a program simulating physics on a d-dimensional grid. For this, I need d nested for loops, which I do not know how to implement!

I hope you can help me, here comes a minimum example of my problem:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#define d X // X can be 1,2,3,... ; chosen before compiling

int main () {

 // ...

 int count[d] , N = Y ; // Y can be 1,2,3,... ; chosen run-time 
	
 for ( count[0] = 0 ; count[0] < N ; count[0]++ )
  for ( count[1] = 0 ; count[1] < N ; count[1]++ )
   for ( count[2] = 0 ; count[2] < N ; count[2]++ )
    // ...
     for ( count[d-1] = 0 ; count[d-1] < N ; count[d-1]++ ) {
      // CODE
     }

 // ...

 return 0;
}


The Code itself is already generalized and compatible with multiple dimensions (depending on the whole count array) and obviously is to be executed Nd times.

Since the source code significantly depends on the value of d, I presume that the preprocessor is needed, but that's pretty much where my knowledge on preprocessors ends.

I hope that some of you can assist me, your help is very appreciated!

Thanks in advance,
strangeopi

PS: I do know about the "rolled up index" technique, but if possible, I would like to avoid that method.
Last edited on
Use recursion.

EDIT: Well, that actually depends on the code you execute. Hmm.....

EDIT: You know you need N^d execution cycles. Just do those:
1
2
3
4
for (int i = 0; i < pow(N, d); i++)
{
    //Code
}


Would that work for the specific code you need?
Last edited on
Not really, the Code itself is generalized to d dimensions, but every step depends on the whole count array (think of it as a vector in d dimensions, and the code for one "point" is depending on all coordinates), i.e. no two single of all Nd steps are the same.

Your suggestion is exactly what I meant by "rolled up index", having one index running through every position in the grid.

This has the advantage of code simplicity, and it is easy to find the rolled up index n to a grid point (n = x0 + x1*N + x2*N2 + ...), but the inverse problem of finding the whole coordinate vector for a specific value of n is more cumbersome.

If there was a preprocessor command that simply produces d for loops as shown above, my problem would be solved, but I fear that is not that simple neither...

Thanks anyways for your suggestion!
If you need the counters for each of the dimensions, that is rather simple too. Inside the for loop, just advance the least significant dimension. If it goes over d, then reset to zero and add one to the next least significant counter, etc. That way you don't have to calculate the indexes, you just have them.
Topic archived. No new replies allowed.