Explain this question please? Wht happened in this program explain please . | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 21

Explain this question please? Wht happened in this program explain please .

https://www.sololearn.com/post/417181/?ref=app

24th May 2020, 8:39 AM
YASH SHAH
YASH SHAH - avatar
4 Answers
+ 5
Because function x is called with same variable in position of both arguments, inside function variables a and b share same memory location. You can see that by adding test to function x: int x(int &a, int &b) { if(&a==&b) cout<<"Same address"<<endl; a=3; b=4; return a+b; } So first (a=3) both get value 3 and then (b=4) both get value 4.
24th May 2020, 12:04 PM
Uros Zivkovic
Uros Zivkovic - avatar
+ 4
You are passing a (a,a) to function x by reference (int &a, int&b), meaning you can change their values in function x. You might be confused because of (int&a, int &b), but you can change the names of these to (int&a, int&y) You are still changing ONLY a because you are passing ONLY a in main int c = x(a,a) And in function x(int&a, int&b) a=3; -------> a = 3 b=4; ---------> a=4; REMEMBER int&b is a name holding a reference to a.
24th May 2020, 9:21 AM
Jay W
+ 3
This question has been asked before and read comments. checkout https://www.sololearn.com/Discuss/2307927/?ref=app
25th May 2020, 3:16 PM
A S Raghuvanshi
A S Raghuvanshi - avatar
+ 1
comments are pretty great:))
26th May 2020, 4:11 AM
Aditya Gautam
Aditya Gautam - avatar