In the following code:
#include <iostream>
using namespace std;
int main()
{
int num = 0;
while (num >= 0 && num <= 3)
{
int inner_loop_count = 0;
cout << "Loop # " << ++inner_loop_count << "\n";
num++;
}
}
The output is:
Loop # 1
Loop # 1
Loop # 1
Loop # 1
My understanding that the loop scope is between the braces {} and cannot be used to define a loop counter, because the declaration and the initialization will be redone each time.
I tried the following solution:
Question #1: Is my understanding correct?
Question #2: Are there any other -technically- possible solutions?
Thanks
You can't practically define a loop counter inside the loop body. A static could work technically in a given context, as you mention. But if the loop was entered a second time that counter would not start at 0.
So instead, use a for loop.
That's what it's “for”:
for( int num = 0; num <= 3; ++num )
{
// ...
}
It's defined by equivalence with a while loop placed in an enclosing braces block where the int num = 0 declaration is placed.
The update ++num is placed at the bottom of the loop body in that equivalent, like this:
// Equivalent:
{
int num = 0;
while( num <= 3 )
{
// ...
++num;
}
}
… which you avoid having to write by using the for.
Your understanding is correct, and another possible solution would be to declare variable outside of a loop:
int inner_loop_count = 0;
while (num >= 0 && num <= 3)
{
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