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?
The problem is that Func()
return
s 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 return
s 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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With