c++for-looprecursionassemblystatements

Create a recursive for statement in c++


I'd like to know if it is actually possible to create / define an homemade for statement in C++. Something similar already have been asked here:

"How to create a for loop like command in C++? #user9282's answer"

What I ask for is if we can make a for that performs as much for as we want (n times).

As example, here is a basic for-loop statement :

for (int i = 0; i < 10; i++) { ... }

I'm wondering if the new for-loop could result more like this :

int x = 20; // individual loops
int y = 3; // = amount of for-loops performed (in this case, 3)

// maybe some code generating for-loops here or something...

// result:
for (int i = 0; i < x; i++)
{
    for (int j = 0; j < x; j++)
    {
        for (int k = 0; k < x; k++)
        {
            // if "y" was equal to 5, there would be 2 more for-loops here
            instructions; // we can use "i", "j", "k", ... here
        }
    }
}

Do you think this could be possible in c++ ?

[EDIT: made clearer the code above]

In one sentence: I want to create a statement (e.g. if, while, for, switch) that puts for-loops into for-loops (just like the code above has for-loops into for-loops) so we can access multiple increments (i, j, k, ...) in the same scope.


Solution

  • You can easily do that with recursive functions that contains a for loop. I would do it like this:

    void foo() {
        for (...) {
            foo();
        }
    }
    

    That way, you can do as many nested for loops as you want.

    However, if you want define a recursive nested for loops in your code without defining an external function, you could use lambdas:

    auto recursive = [](auto func) {
        // This is needed to make a recursive lambda
        return [=](auto... args){
            func(func, args...);
        };
    };
    
    auto nestedForLoop = recursive([](auto self){
        // Here's your recursive loop!
        for (...) {
            self();
        }
    });
    
    // You can simply call `nestedForLoop` to execute loop
    nestedForLoop();