I'll try to explain. The pointers are really fun and powerful if you have enough patience:
fn1(x,y,&z);
cout<< x<< " " << y<< " "<< z<< endl;
// output: 8 7 8 (I dont get this part!!!)
Let's take a look at our function fn1
int fn1(int &a, int b, int *c){
a=b++;
b+=7;
*c= ++a;
return b;
}
First, note that in fn1(int &a)
variable a is passed by reference, not by value. This means that we will directly operate with the value that we pass on a. It basically means that if you change the value of a inside the function, the change will persist. So since int x=4, y=7, z=14;
and we call fn1(x, y, &z)
, we pass the Variable x to a (think of it as renaming it temporarily from x to a). So a
is initially 4. b is simply a value, so the contents of y is passed to b and *c is a pointer and simply takes as value the physical address of z (that's why you have fn1(&z)
).
So when we call our function fn1(x, y, &z)
we execute:
a=b++;
So a changes to 7, b changes to 8. (if this is confusing, read an intro about operators this)
Then:
b+=7; //same as: b=b+7;
So b takes value 8+7=?? (sorry! I don't have a degree in Math!)
Finally:
*c= ++a;
Now, since we have ++a, first a changes to a=a+1 and now takes the value of 8, since it was 7! And the *c means "the value of the variable that pointer c points to": so the value of the variable that c points to is z
. So the value of z is changed to whatever a is (which is 8).
And now the final step (for real this time). Why didn't y
change?
Because we fn1
takes b by value, not by reference, and when the function ends, var b gets destroyed.
Now try to do the second part:
y=fn1(x,y,&z);
In this case y will take whatever fn1 returns!
I'd really advise you take a step by step approach. If it's still confusing, exercise separately with the behaviour of each type of var passing it by ref, by val and later by pointer.