Search code examples
c++loopsiterationstatic-variables

how to iterate one time over a loop each time call a function?


I have loop and want to iterate one time each time I call the function. This is my code:

#include <iostream>

void iter(int max_i, int max_j){

        static int i = 0;
        static int j = 0;
        for (; i< max_i; i++ ){
                for(; i<max_j; j++){
                        std::cout << i << " " << j << std::endl;
                        return;
                }
        }
}


int main(){

        iter(4,4);
        iter(4,4);
        iter(4,4);
        return 0;

}

But the result shows that each time the function is called it starts from zero.

amirreza@time:/tmp$ g++ iterate.cpp 
amirreza@time:/tmp$ ./a.out 
0 0
0 0
0 0

Solution

  • From your code, it should be

    void iter(int max_i, int max_j){
        static int i = 0;
        static int j = 0;
    
        if (i < max_i)
        {
            std::cout << i << " " << j << std::endl;
            if (++j >= max_j) {
                ++i;
                j = 0;
            }
        }
    }
    

    Demo

    Better to have all those variables in class to avoid static which might be problematic. Something like:

    truct IterData
    {
        const int max_i;
        const int max_j;
        int i = 0;
        int j = 0;
    };
    
    bool iter(IterData& data){
        std::cout << data.i << " " << data.j << std::endl;
        if (++data.j >= data.max_j) {
            ++data.i;
            data.j = 0;
        }
        return data.i < data.max_i;
    }
    
    int main()
    {
        IterData data{4, 4};
    
        while (iter(data));
    }
    

    Demo

    C++20 has co-routine to allow to write the loop most naturally.