Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static Variable & For Loop

Tags:

c++

static

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?

like image 409
Hyden Avatar asked Dec 23 '22 18:12

Hyden


2 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.

like image 153
songyuanyao Avatar answered Jan 12 '23 11:01

songyuanyao


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).

like image 31
463035818_is_not_a_number Avatar answered Jan 12 '23 11:01

463035818_is_not_a_number