0

Can someone explain why 'b' is not 7 in the output of the below C++ code ? (1619 is the answer btw)

#include <iostream> using namespace std; int fun(int &a, const int &b) { a*=b; return b+3; } int main() { int x = 4; int y = fun(x,x); cout << x << y; return 0; }

24th Feb 2020, 10:00 PM
Harshal P
Harshal P - avatar
2 Answers
+ 6
It's because &a and &b are "x". &a <---> x &b <---> x a*=b ; // 4*4 =16 // then x=16 then b=16. return b+3 ; // 16+3=19 If you change "a" then you change "x". So if you changed "a" then you changed "b".
24th Feb 2020, 10:11 PM
Pedro H.J
Pedro H.J - avatar
+ 2
because a and b are using same reference variable. quote from geeksforgeeks ``` A reference is same object, just with a different name and reference must refer to an object``` [ https://www.geeksforgeeks.org/passing-by-pointer-vs-passing-by-reference-in-c/ ]
24th Feb 2020, 10:12 PM
Taste
Taste - avatar