Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ declaration and initialization variables inside while loops

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:

  1. using static keyword. (Regardless of goodness or badness).
  2. including while itself inside outer {} and declare the counter variable there just right before while.

Question #1: Is my understanding correct?
Question #2: Are there any other -technically- possible solutions?

Thanks

like image 797
Shadi Avatar asked Aug 10 '26 09:08

Shadi


2 Answers

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.

like image 80
Cheers and hth. - Alf Avatar answered Aug 12 '26 22:08

Cheers and hth. - Alf


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)
{
like image 34
Ilya Kobelevskiy Avatar answered Aug 13 '26 00:08

Ilya Kobelevskiy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!