Pass by value or reference?

Can someone explain to me why the output of this program is 20 3 40?Thanks~


#include<iostream>

using namespace std;

void fun(int&d, int e, int *f)
{
d*=10;
e*=10;
*f*=10;
}

int main()
{
int a=2, b=3,c=4;

fun(a,b,&c);

cout<<a<<b<<c;

return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include<iostream>

using namespace std;

void fun(int &d, // passed by reference (the identifier is "used" rather than the value it refers to)
            int e, // passed by value (the value is copied and thus there's no way it has a relation to the inputted variable
            int *f // passed by pointer (practically the same as passing by reference, except that you have pointer functionality in the function)
            )
{
   d *=10;
   e *=10;
   *f *=10;
}

int main()
{
   int a=2, b=3,c=4;
   fun(a,b,&c);
   cout<<a<<b<<c;
   return 0;
}


This means that the first and last are used rather than copied. Thus allowing fun() to change the values they store. The process flow is kind of like this:
main() starts.
int a = 2
int b = 3
int c = 4
-- Function --
a and c are carried over, b's value is copied (they are respectively referred to as d, e and f in this function)
d = d * 10 => d = 20
e = e * 10 => e = 30
value in f = f * 10 => f = 40
-- Function end -- d and f are "sent back" as a and c
a == 20
b == 3 (because you copied the value, and didnt tell the function that you were sending a variable)
c == 40
Last edited on
Thanks for ur explanations, it is very clear:)
Topic archived. No new replies allowed.