edited by
1,694 views
0 votes
0 votes

Consider the following two $C++$ programs $P1$ and $P2$ and two statements $S1$ and $S2$ about these programs:

$P1$ $P2$

void f(int a, int *b, int &c)

{

a=1;

*b=2;

c=3;

}

int main()

{

int i=0;

f(i, &i, i);

count <<i;

}

double a=1, b=2;

double &f(double &d)

{

d=4;

return b;

}

int main()

{

f(a)=5;

count < < a< < “:” < < b;

}

$S1$ : $P1$ prints out $3.$

$S2$ : $P2$ prints out $4:2$

What can you say about the statements $S1$ and $S2$?

$Code:$

  1. Only $S1$ is true
  2. Only $S2$ is true
  3. Both $S1$ and $S2$ are true
  4. Neither $S1$ nor $S2$ is true
edited by

1 Answer

3 votes
3 votes
f(i,&i,i); --> f(int a,int *b,int &c);

$'a'$ gets the copy of the variable passed

$'b'$ points to the variable passed to it i.e. to $i$

$\&c$ passing $i$ by reference

a = 1; //updates the value of the copy of i, original i is unaffected
*b = 2; //updates the original i i.e i = 2;
c = 3; //updates the original i i.e. i=3;
..
cout<<i;

This will print $i=3$. So, $S1$ is true

f(a) = 5;

$f(a)$ calls the function $f$

double &f(double &d){
    d=4;
    return b;
}

This function takes a reference variable as a parameter, updates it's value to $4$ i.e. $a=4$ and returns a reference to $double\,b$

f(a)=5; //updates the value of b i.e b = 5

cout<<a<<":"<<b; //prints 4 : 5

So, $S2$ should be false

So, $A$ should be the answer.

Correct me if I'm wrong.

Related questions

1 votes
1 votes
0 answers
3
0 votes
0 votes
2 answers
4
Arjun asked Jan 2, 2019
4,405 views
Consider the graph shown below:Use Kruskal’s algorithm to find the minimum spanning tree of the graph. The weight of this minimum spanning tree is$17$$14$$16$$13$