I am trying to understand the scope of the for loop by testing out the following three examples:
Example 1:
int a=15; for(a=1;a<3;a++) { cout<<a<<endl; } cout<<a<<endl; Here the console displays 1 2 3. However, I would have thought that it should display 1 2 15, since normally it seems that the scope of the variable a inside the for loop remains inside the for loop.
Example 2:
for (int a=1; a<3; a++) { cout<<a<<endl; } cout<<a<<endl; In this example the compiler does not recognize the variable a after the for loop - as expected. So how was it able to be recognised it in Example 1?
Example 3:
int a=15; for(int a=1;a<3;a++) { cout<<a<<endl; } cout<<a<<endl; In this case the console displays 1 2 15. What is the difference between this and Example 1?
Thank you in advance for your help.