Assuming the exam-intended left-to-right evaluation of the multiplication…
2017
Assuming the exam-intended left-to-right evaluation of the multiplication expression, what is the expected output of this C++ program?
#include <iostream>
using namespace std;
void square(int *x)
{
*x = (*x)++ * (*x);
}
void square(int *x, int *y)
{
*x = (*x) * --(*y);
}
int main()
{
int number = 30;
square(&number, &number);
cout << number;
return 0;
}
- A.
910
- B.
920
- C.
870
- D.
900
Attempted by 167 students.
Show answer & explanation
Correct answer: C
The overloaded function square(int*, int*) is selected because two pointer arguments are passed. Both x and y contain the address of the same variable, number.
Under the exam-intended left-to-right evaluation used by these options:
1. (*x) reads number as 30.
2. --(*y) decrements the same variable to 29 and yields 29.
3. The product is 30 × 29 = 870, and this value is stored in number.
So the expected output is 870, i.e. option C.
Strict C++ note: when x and y alias the same object, the expression (*x) * --(*y) involves an unsequenced read and modification of the same scalar object. Therefore, strictly according to the C++ standard, the behavior is undefined. The listed answer follows the exam-intended evaluation.