Scope of variables declared inside loop
Reuse of variable declared in a loop scope for another loop.
Learning Objectives
- Understanding scope of variables declared and/or initialised within a loop.
Source Code
|
|
Run Output
Code Understanding
for(int i=1;i<=10;++i)
This is first loop. Here int i is declared as first instruction and its scope is considered to be inside the given loop only.
int x=5;
The int x=5 declaration here is again specific to this loop. Also it may look like a re-declaration of variable when the loop iterates again, but c++ compiler considers it one declaration only.
cout<<i+x<<” “;
This prints sum of iteration index i summed with internally declared variable.
cout<<endl;
This line creates a new line, so that the new loop output comes in a new line.
for(int i=1;i<=10;++i)
This is second loop. Here the int i is declared again as the scope of this is limited to this particular loop.
int x=10;
This is considered another variable as the scope of variable is reserved for within this loop only.
cout<<i+x<<” “;
This time the loop will print the new index value in the scope of second for loop summed with new value of x;
Notes
- The scope limitation of variable and thus the re-usability of variables has come as per the ANSI standards. This is different in old TurboC type of compilers which do not follow such standards.
Suggested Filename(s): var-dec-in-loop.cpp
Created: 1-Jan-2018 22:29 | Updated: 1-Jan-2018 22:29|
