Consider the following two C++ programs P1 and P2 and two statements S1 and S2…
2018
Consider the following two C++ programs P1 and P2 and two statements S1 and S2 about these programs:
Program P1
void f(int a, int *b, int &c)
{
a = 1;
*b = 2;
c = 3;
}
int main()
{
int i = 0;
f(i, &i, i);
cout << i;
}Program P2
double a = 1, b = 2;
double &f(double &d)
{
d = 4;
return b;
}
int main()
{
f(a) = 5;
cout << a << ":" << b;
}Statements
S1: P1 prints out 3
S2: P2 prints out 4:2
Answer: D. Only S1 is true — Program P1 passes the variable i by value, pointer, and reference. The parameter a is passed by value, so its assignment to 1 does not affect i. However, the…
- A.
Neither S1 nor S2 is true
- B.
Only S2 is true
- C.
Both S1 and S2 are true
- D.
Only S1 is true
Attempted by 126 students.
Show answer & explanation
Correct answer: D
Program P1 passes the variable i by value, pointer, and reference. The parameter a is passed by value, so its assignment to 1 does not affect i. However, the pointer parameter b points to i, so *b = 2 updates i to 2. The reference parameter c refers directly to i, so c = 3 updates i to 3. Consequently, the program prints 3, making statement S1 true.\nIn Program P2, f(a) modifies the local reference d (which is a alias for global variable a) to 4. The function then returns a reference to the global variable b. When we execute f(a) = 5, we are assigning 5 to the returned reference of b. Thus, a becomes 4 and b becomes 5. The output is "4:5", making statement S2 false.\nSince only S1 is true, the correct option is D.
A video solution is available for this question — log in and enroll to watch it.
Explore the full course: Mppsc Assistant Professor Computer Science Paper 2