I have read about scope and have thought that I understood it up to now. I had a problem with another program and while trying to fix it I found that variables in the scope of a loop behave quite unusually to what I expected. So I made this program to show what I mean:
#include <iostream>
using namespace std;
int main()
{
int num = 6;
for (int i = 0; i < 5; i++)
{
cout << num;
int num = 5;
cout << num;
}
}
I expected for the first run through of the for loop, the first cout << num would be undefined as it is a new scope and num hasn't been defined yet. But instead, it just used the value of num from the previous scope. Then when num is initialized to 5 inside of the loop, after that, all the outputs for num should be 5. But instead the output was 656565...
So using this information I made a model of what I think the scope of variables worked like and it looks like this:
So in the image you can see how I think the scope works and I think that for each iteration through the loop, the loop gets a new scope of variables and then removes its scope at the end of the loop and gets a new one at the beginning of the next iteration which explain why the for loop uses num from the previous scope until num is re-initialized in the current scope. Is my understanding correct?