+ 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; }
6 Respuestas
+ 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)
+ 3
Happy to help 😃
+ 2
That makes sense. :) Thank you very much Rishi
+ 2
Manav Roy why are you asking this? Am just a college boy who knows a bit of Programming 😗
+ 1
Manav Roy Learning cpp just for fun actually. My real job is being a teacher :)