[Scoping] Consider the following program

Scoping

Question

a) Which statements cause a compile error? Explain the reasons of errors.
b) If the incorrect statement is discarded, what will be written on the screen when the C++
program is compiled and run? Check your answer using a compiler.

#include <iostream>

using namespace std;

int k=1;

int f(int a){

return k+a;

}

int main(){

int k = 2;

::k=3;

cout << k << endl;

{

int k = 10;

cout << k << endl;

{

int k = 15;

cout << k << endl;

{

cout << k << endl;

}

}

cout << k << endl;

}

for (int j=0; j<3; j++){

int k = j-15;

cout << k << endl;

}

int k = 2;

cout << k << endl;

cout<<f(k)<<endl;

cout<<j<<endl;

return 0;

}

Solution

#include <iostream>

using namespace std;

int k=1;

int f(int a){

return k+a;

}

int main(){

int k = 2;

::k=3;

cout << k << endl;

{

int k = 10;

cout << k << endl;

{

int k = 15;

cout << k << endl;

{

cout << k << endl;

}

}

cout << k << endl;

}

for (int j=0; j<3; j++){

int k = j-15;

cout << k << endl;

}

A: int k = 2;

cout << k << endl;

cout<<f(k)<<endl;

B: cout<<j<<endl;

return 0;

}

a) Which statements cause a compile error? Explain the reasons of errors.

Answer:

A: k is redefined.

B: j is not defined in this scope. J is defined in the scope of
for-loop

 

b) If the incorrect statement is discarded, what will be written on the screen when the C++
program is compiled and run? Check your answer using a compiler.

Answer:

2

10

15

15

10

-15

-14

-13

2

5

Advertisements

Posted on October 13, 2013, in Örnekler, C++ and tagged , , . Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: