Search code examples
c++for-loopnested-loopsfunction-definition

Use function argument as loop variable in C++


foo uses function argument as loop variables

void foo(int i, int j) {
    for (; i < 5; ++i)
        for (; j < 5; ++j)
            std::cout << i << " " << j << std::endl;
}

and foo(0, 0) prints

0 0
0 1
0 2
0 3
0 4

I was wondering why i is always 0.


Solution

  • I was wondering why i is always 0.

    You are mistaken. The variable i is changed within the function from 0 to 5.:)

    The problem is that after the first execution of the inner for loop

     for (; j < 5; ++j)
            std::cout << i << " " << j << std::endl;
    

    the variable j becomes equal to 5. As a result in all other iterations of the outer for loop the inner for loop is skipped.

    To get the expected result you could write for example within the function

    void foo(int i, int j) {
        for (; i < 5; ++i)
            for ( int k = j; k < 5; ++k)
                std::cout << i << " " << k << std::endl;
    }