+ 2

What is happening exactly...? Function - pass by reference

I have a void function that outputs two variables. When I pass in a variable 'a' twice, the function just outputs 'b' from within the function. Why is this happening? #include <iostream> void f(int &a, int &b) { a = 4; b = 10; std::cout << a << b << std::endl; } int main() { int a = 6; f(a, a); //output: 1010 return 0; }

31st Jan 2022, 9:11 AM
The_Fox
The_Fox - avatar
8 ответов
+ 7
You are passing a by reference to the function twice, so as a result you get a and b both referring your main function's 'a'. Now you change a(inside f) to 4. So now you're a(inside main) becomes 4 too. Since b is also referring to a(inside main), b too is changed to 4. So now, a(inside f)=4 b(inside f)=4 a(inside main)=4 Now you make b=10, b refers to a(inside main) so you're main function a becomes 10 too. Your a(inside f) refers to the a(inside main) so it too changes to 10. So now the status of the variables is: a(inside f)=10 b(inside f)=10 a(inside main)=10 You're printing a(inside f) and b(inside f) so you get the output 1010(without any space)
31st Jan 2022, 10:15 AM
Rishi
Rishi - avatar
+ 3
Happy to help 😃
31st Jan 2022, 10:21 AM
Rishi
Rishi - avatar
+ 2
That makes sense. :) Thank you very much Rishi
31st Jan 2022, 10:19 AM
The_Fox
The_Fox - avatar
+ 2
Manav Roy why are you asking this? Am just a college boy who knows a bit of Programming 😗
1st Feb 2022, 9:10 AM
Rishi
Rishi - avatar
+ 2
Manav Roy I learnt some Python in my high school days, it was in my 12th grade syllabus, forgot it right away. I learn a good amount of C++ last year, then i learn some Java 2 or 3 months back. When did I start? I would say an year back
1st Feb 2022, 10:16 AM
Rishi
Rishi - avatar
+ 1
Manav Roy Learning cpp just for fun actually. My real job is being a teacher :)
1st Feb 2022, 12:07 PM
The_Fox
The_Fox - avatar