Answer to Question #43660 in C++ for C+ help i'm lost? Scope of Variable Names

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
1
Expert's answer
2014-07-02T13:54:24-0400
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
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS