#include <iostream>usingnamespace std;
int main()
{
// Up here, x is not in scope.// x = 0; // Error// Declare variableint x;
// Scope of a variable is the locations in the program// where you can access it.// For 'x', up to the closing brace of main.
x++; // OK
x = 9;
if(x == 5) // x is in scope
{
int y = x+1;
// y is in scope for the rest of this// block in which it is declared.
}
// Once I leave the declaring block of y,// y is NOT in scope.//y++; // ERROR// What about loops?int i; // declare loop variablefor(i = 0; i < 5; i++) // use loop variable
{
}
// Can also access loop variable herefor(int j = 0; j < 5; j++) // declare and use loop var
{
cout << j << "\n"; // can use loop var
}
// After loop, variable j is out of scope.// Cannot do a similar trick with while loops.int k = 0;
while(k < 5)
{
k++;
}
// Can have two distinct vars with same name,// as long as the scopes are different.int myquiz = 99; // scope is mainif(myquiz > 80) {
float myquiz = 2.35;
cout << myquiz << "\n"; // refers to innermost in scope
}
cout << myquiz << "\n"; // refers to previous scope, the intreturn0;
}