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 }
Comments