Not too difficult to implement with recursion, although this still seems like a weird use case.
In any case, this makes the code as clear as possible, being "infinitely" extensible *
Each cycle has its own functionality (although it is identical), as you pointed out in the comments to the other answers.
void do_loop(std::vector<int> *loop_vars, int loop_level, int max_loop_level, int loop_iter_limit, void* data) { while(loop_vars[loop_level] < loop_iter_limit) { //do work on *data *loop_vars[loop_level]++; do_loop(loop_vars, loop_level+1, max_loop_level, loop_iter_limit, data); } else { return; } } void nestedloops(int loop_count, loop_limit, void* data) { std::vector<int> vars; for (int i = 0; i<loop_count; i++) vars.pushback(0); do_loop(&vars, 0, loop_count, loop_limit, data); return; }
a call using nestedloops(5,10,data); , for example, to execute 5 nested loops with 10 iterations per loop.
You will want to change void* data to something more suitable (I don't know what kind of work you will do). When manipulating data, loop variables ( i,j,k... ) are set by a vector, therefore instead of:
for (int i = 0; i<max; i++) { for (int j = 0; j<max; j++) { x += i+j; } }
you would replace the job (in this case x=i+j ) with
*data += loop_vars[0]+loop_vars[1];
void* data will be changed to int* data
and instead of loops you should call
nestedloops(2,max,&x);
Please comment if you need clarification.
* not sure if the compiler will be able to perform tail call elimination , if it is not, you are limited by the depth of the stack. However, I think that 500 (GCC by default) has enough nested loops to start with them, and it can be set higher, but again I donβt know your use case, and the execution time will be horrified to this point.