Static Variable & For Loop

Viewed 122

I've produced a minimum reproducible example of my problem:

#include <iostream>

void Func()
{
    static int i = 0;

    for (i; i < 5; i++)
    {
        std::cout << i << "\n";
        return;
    }
}

int main()
{
    Func();
    Func();
    Func();
}

The output from this is "0", "0", "0". I want it to output "0", "1", "2". How do I achieve this?

3 Answers

The problem is that Func() returns immediately after i is printed out, i++ (as the iteration_expression of for loop) is not evaluated at all.

You might want (even the loop seems meaningless here, the function always returns at the 1st iteration) :

void Func()
{
    static int i = 0;

    for (;i < 5;)
    {
        std::cout << i << "\n";
        i++;
        return;
    }
}

Or

void Func()
{
    static int i = 0;

    for (;i < 5;)
    {
        std::cout << i++ << "\n";
        return;
    }
}

PS: I'm not sure about your intent, but as @FrançoisAndrieux and @Jarod42 commented, using if or while seems to make more sense, if you want i to be increased everytime Func() is called but won't be larger than 5.

Your for loop is equivalent to:

while (  i < 5 ) {
    // loop body
    std::cout << i << "\n";
    return;
    // increment
    i++;    
} 

In other words, you never modify i because you return before. You can get the wanted output if you rearrange the above while loop (or get rid of the loop altogether).

The problem with your for loop is that it never reaches its end (the return statement prevents that). Thus, the i++ operation, which would be executed after the body of the loop completes, is never being used.

To achieve your desired output, but keeping the for loop, you would need something like the following code (but this makes the loop even more bizarre):

void Func()
{
    static int i = 0;
    for (; i < 5; ) {
        std::cout << i << "\n";
        i++;
        return;
    }
}
Related