CPA-21-02 practice question 14 of 35

What happens when you attempt to compile and run the following code? #include using namespace std; void fun(int &i); int main() { int i=2; fun(i); cout

Full set: 257 questions
Answer options
A: It prints: 2
B: It prints: 0
C: It prints: 4 Correct answer
D: It prints: 16
Correct Answer:
C. It prints: 4
Explanation

The program demonstrates pass-by-reference in C++. The function fun is declared and defined to accept an integer reference (int &i) as its parameter. When fun(i) is called in main, the reference parameter binds directly to the original variable i in main (which is initialized to 2). Inside the function, the compound assignment operator i += 2 adds 2 to the referenced variable, modifying the original i in main from 2 to 4. After the function returns, cout << i; prints the modified value, which is 4.

Why Incorrect

A. Incorrect because the parameter is passed by reference, meaning the modification inside the function affects the original variable.
B. Incorrect because the function adds 2 to the variable; it does not reset or subtract from it to reach 0.
D. Incorrect because the operation is addition (2 + 2 = 4), not exponentiation or multiplication yielding 16.

References

1. ISO/IEC 14882:2017 (C++17 Standard), Section 11.3.3 [dcl.ref], Paragraph 1-4 (References).

2. ISO/IEC 14882:2017 (C++17 Standard), Section 8.2.2 [expr.call], Paragraph 4 (Function call and parameter passing).

3. Stanford University CS106L Standard C++ Programming, Lecture 3: References and Const.

Scroll to Top