Question #43660

C++ Investigate the operation of scope rules in a program.


// VariableNameScope

#include <iostream>

using namespace std;

int i = 111;

int main()
{
{
int i = 222;
{
int i = 333;
cout << "i = " << i << endl;
{
int i = 444;
cout << "i = " << i << endl;
{
cout << "i = " << i << endl;
}
}
}

cout << "i = " << i << endl;
}

cout << "i = " << i << endl;

return 0;
}


Q1: What are the scope rules you observed in the program?

i want to say Global scope(int i = 111;),Local scope (int i = 333;), and function scope (int i = 222;) but now, i'm confused. I really don't understand what is this question asking me. Can somebody help me break it down

Expert's answer

Each block creates its own scope. Variables created before the block will be visible and can be used in all nested blocks. If you create a variable inside a block with the same name as the outside will be used only one that has been defined inside!Exaple int main (){      int x = 5;   // Create outside variable ,this variable can be used in all nested blocks!   cout<<"X = "<<x<<endl;//X = 5   {      cout<<"X = "<<x<<endl;//On display you can see 5 , because variable x not redefine        int x = 3;//redefine variable ,now this variable can be used in all nested blocks!      cout<<"X = "<<x<<endl;//X = 3      {         cout<<"X = "<<x<<endl;//On display you can see 3 , because variable x not redefine           int x = 0;//redefine variable ,now this variable can be used in all nested blocks!         cout<<"X = "<<x<<endl;//X = 0      }      //when end of block; variable x saved outside value       cout<<"X = "<<x<<endl;//X = 3   }   //when end of block; variable x saved outside value    cout<<"X = "<<x<<endl;//X = 3   return 0;}in your example :#include <iostream>using namespace std;int i = 111;// define global variable int main(){   { // create block - 1      int i = 222;//redefine variable i and now this variable can be used in all nested blocks!       {// create block - 2          int i = 333;//redefine variable i and now this variable can be used in all nested blocks!          cout << "i = " << i << endl;//print redefine(in block - 2 )  variable          {// create block - 3             int i = 444;//redefine variable i and now this variable can be used in all nested blocks!            cout << "i = " << i << endl;//print redefine(in block - 3 )  variable             {               cout << "i = " << i << endl;//print define(in block - 3 )  variable             }         }      }      cout << "i = " << i << endl;//print define(in block - 1 )  variable    }   cout << "i = " << i << endl;//print  global define  variable }
LATEST TUTORIALS
APPROVED BY CLIENTS