Consider the following code: int sum(int a, int& b) { b += 5; a += 3; return a+b
ID: 3695424 • Letter: C
Question
Consider the following code:
int sum(int a, int& b) {
b += 5;
a += 3;
return a+b;
}
int main()
{ int x = 5;
int y = 1;
cout<<x<<" "<<y<<" "<<sum(x,y);
return 0;
}
20. Which of the following statements is True?
a. x is passed by value and y is passed by reference
b. x and y are both passed by reference
c. x and y are both passed by value
d. y is passed by value and x is passed by reference
21. What are the values of a and b at the end of function execution?
a. 5 1
b. 1 5
c. 8 6
d. 8 8
22. What are the values of x and y after the function call?
a. 5 1
b. 5 6
c. 8 1
d. 8 6
23. What is the output?
a. 8 8 16
b. 5 6 14
c. 5 1 6
d. 8 1 9
the answer is acbb
can you explain the reason?
thanks so much
Explanation / Answer
20) For the function sum, the definition is int sum(int a, int& b). We can see that the first argument is taking an int and second one is taking int &. The second definition means that the value is passed by reference.
21) At the start of the function the value of a will be equal to x which 5 and b will be equal to value of y which is 1. So a+=3 will make the value of a as 8 and b+=5 will make the value of b as 6.
22) As x is passed as value although the value of a is also 5 intially a new interger is created in the memory and the value of x is copied in to that memory. In the case of y as it is passed by reference no new memory is created any changes will be made to the same memory location. So the value of x will be unchanged and the value of y will be 6.
23) As we know that the value of a is 8 and the value of b is 6 at the end of the function. Their sum is 14. Also in cout all the expressions are evaluated before printing the final output, so by the time of printing the value of y will already be 6 because of function call. So the output is 5 6 14.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.