What will be the output of the following C++ code? #include <iostream> using…

2023

What will be the output of the following C++ code? #include <iostream> using namespace std; void square (int *x, int *y) { *x = (*x) * --(*y); } int main() { int number = 30; square(&number, &number); cout << number; return 0; }

  1. A.

    30

  2. B.

    870

  3. C.

    Segmentation fault

  4. D.

    More than one of the above

  5. E.

    None of the above

Attempted by 100 students.

Show answer & explanation

Correct answer: B

Concept: call by pointer and pre-decrement

Passing by pointer hands the function the address of the caller's variable, so dereferencing (*p) reads and writes that same variable in place. The pre-decrement --(*p) lowers the pointed-to value by 1 first. When the SAME address is passed for two parameters, both pointers alias one variable, and the function's write is reflected back to that variable in the caller.

Application to this code

  1. number = 30. The call square(&number, &number) passes the address of number to both x and y, so *x and *y both name number.

  2. The body *x = (*x) * --(*y) is evaluated under the conventional left-to-right reading this item's published answer key assumes: the multiplicand is taken as the original 30 and --(*y) lowers the value to 29.

  3. The product 30 * 29 = 870 is written through *x back into number.

  4. main then prints number, which now holds 870.

Cross-check

Because both pointers alias number, the in-place write persists after the function returns, giving the printed value 870 = 30 * 29 under this item's assumed evaluation order. Caveat: strictly under the ISO C++ standard, (*x) and --(*y) are unsequenced operands of the same multiplication and both touch the same aliased object, so the expression is formally undefined behaviour and a conforming compiler is not obligated to produce 870. 870 is nonetheless the standard published answer for this widely-reused argument-passing item (this exact program is the well-known ISRO CS 2017-May pointer-aliasing question); it is treated here as the exam-convention answer rather than a language-guaranteed one.

Explore the full course: Uppsc Polytechnic Lecturer 2025 Cs