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 questionsThe 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.
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.
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.
Keep practicing
Take the free CPA-21-02 practice test
Ten exam-style questions with answers and explanations, plus the exam facts and study guides.
More questions
Other CPA-21-02 practice questions
- Question 1What happens when you attempt to compile and run the following code? #include using names…
- Question 2What happens when you attempt to compile and run the following code? #include #include us…
- Question 3Which of the following statements are correct about an array? int tab[10];
- Question 4What happens when you attempt to compile and run the following code? #include #include us…
- Question 5What is the output of the program if characters 'h', 'e', 'l', 'l' , 'o' and enter are su…
- Question 6What happens when you attempt to compile and run the following code? #include using names…
