C++ Same name local variables keeping values between loops

76 Views Asked by At

I have the following 2 loops in my C++ code:

for (int hcount = 0; hcount < height; hcount++)
    {
        for (count = 0; count < width; count++)
        {
            cout << character;
        }
        cout << endl;
    }

cout << endl;

for (int hcount = 0; hcount < height; hcount++);
{
    for (count = 0; count < width; count++)
    {
        cout << character;
    }
    cout << endl;
}

The problem I am running into is that after using the variable hcount in the first loop, the variable hcount in the second loop will initialize with the value it had in the first loop. I am not sure why this is as both are being initialized as what would seem to be local variables and set equal to 0.

1

There are 1 best solutions below

0
On BEST ANSWER

The problem is here:

for (int hcount = 0; hcount < height; hcount++);

You end the loop with ;, which is a no-op. The hcount is in any case visible only in the scope of the loop. After the loop execution (i.e. after ;), the inner loop starts executing. Your debugger probably displays the last value taken by hcount.