can anyone explain this output? #include <iostream> using namespace std; int x(int &a,int &b) { a=3; b=4; return a+b; } int main() { int a=2; int b=7; int c=x(a,a); cout <<a<<endl<<b<<endl<<c; } output:- 4 7 8 | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

can anyone explain this output? #include <iostream> using namespace std; int x(int &a,int &b) { a=3; b=4; return a+b; } int main() { int a=2; int b=7; int c=x(a,a); cout <<a<<endl<<b<<endl<<c; } output:- 4 7 8

23rd Aug 2016, 11:23 AM
Lekhraj Singh
Lekhraj Singh - avatar
2 Answers
+ 1
The function x gets the adress (referenced) of a (main a) two times. Then modifies the real value of a (main a) (through it adress) with value of 3. b (function b) for this call also has a (main a) adress and modifies it with value 4. returns 4+4. Main b hasn't been modified so it outputs a =4, b=7 and c=8
24th Aug 2016, 3:58 PM
Néstor
Néstor - avatar
+ 1
When f() is called with a as both parameters, both arguments refer to the same variable. This is known as aliasing. First, a is set to 3, then a is set to 4, then 4+4 is returned. b is never modified.
10th Dec 2017, 3:45 AM
Veronika Kolimova
Veronika Kolimova - avatar