SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Walter Savitch ,julia Lobur
Chapter:
More Flow Of Control
Exercise:
Self-test Exercises
Question:20 | ISBN:9780321531346 | Edition: 7

Question

Though we urge you not to program using this style, we are providing an

exercise that uses nested blocks to help you understand the scope rules.

Give the output that this code fragment would produce if embedded in an

otherwise complete, correct program.

{

int x = 1;

cout << x << endl;

{

cout << x << endl;

int x = 2;

cout << x << endl;

{

cout << x << endl;

int x = 3;

cout << x << endl;

}

cout << x << endl;

}

cout << x << endl;

}

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

It helps to slightly change the code fragment to understand to which declaration:

 

each usage resolves.

{
	int x1 = 1;// output in this column
	cout << x1 << endl;// 1<cr>
	{
		cout << x1 << endl;// 1<cr>
		int x2 = 2;
		cout << x2 << endl;// 2<cr>
		{
			cout << x2 << endl;// 2<cr>
			int x3 = 3;
			cout << x3 << endl;// 3<cr>
		}
		cout << x2 << endl;// 2<cr>
	}
	cout << x1 << endl;// 1<cr>
}

Here <cr > indicates that the output starts a new line.

0 0

Discussions

Post the discussion to improve the above solution.