Consider the following two C++ programs P1 and P2 and two statements S1…
2018
Consider the following two C++ programs P1 and P2 and two statements S1 and S2 about the programs :

S1: P1 prints out 3
S2: P2 prints out 4 2
What can you say about the statements S1 and S2 ?
- A.
Only S1 is true
- B.
Only S2 is true
- C.
Both S1 and S2 are true
- D.
Neither S1 nor S2 is true
Attempted by 42 students.
Show answer & explanation
Correct answer: A
P1 — reasoning: Function f has parameters: a passed by value, b as a pointer, and c as a reference. In main, i is initialized to 0 and f is called as f(i, &i, i).
a = 1 sets only the local copy of a (no effect on i).
*b = 2 writes through the pointer to the object i (sets i = 2).
c = 3 assigns through the reference to i (sets i = 3).
After the call, i becomes 3, so the first program prints 3.
P2 — reasoning: Here a = 1 and b = 2. Function f takes a reference d, sets d = 4, and returns b by reference (return type is double&).
Calling f(a) sets a = 4 because d is a reference to a.
f returns a reference to b, so the assignment f(a) = 5 stores 5 into b (sets b = 5).
Therefore after f(a) = 5, a = 4 and b = 5, and the program prints 4:5 (not 4:2).
Conclusion: Only the statement that the first program prints 3 is true. The second statement (that the second program prints 4:2) is false.
A video solution is available for this question — log in and enroll to watch it.