Reputation: 1771
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
Upvotes: 3
Views: 30210
Reputation: 62472
Your understanding is correct. Another possible solution is to use a for
loop:
using namespace std;
int main()
{
for(int num = 0, inner_loop_count = 1; num <=3; num++, inner_loop_count++)
{
cout << "Loop # " << inner_loop_count << "\n";
}
return 0;
}
Upvotes: 1
Reputation: 238311
A1. Yes, your understanding is spot on. An automatic variable is local to its block (delimited by {}
), so it cannot be used as a loop counter if declared within the loop body.
A2. Your 2. suggestion is the typical way to use a counter in a while
loop, although isolating the counter with an outer block is usually not necessary. Another possibility: for
loop control structure, which does exactly the same, with different syntax (i.e. it is syntactic sugar).
Also, you can use a global variable - which is quite similar to using a local static variable.
Upvotes: 0
Reputation: 1864
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.
You are correct
You can declare you counter outside your while loop like this:
int inner_loop_count = 0;
while (num >= 0 && num <= 3)
{
cout << "Loop # " << ++inner_loop_count << "\n"; //beware..Counts +1 before loop is done. First looping will count as 1, but is actually number 0
num++;
}
Upvotes: 0
Reputation: 145249
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
.
Upvotes: 2
Reputation: 5345
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)
{
Upvotes: 1