So why not walk through this and see if we can understand what is happening.
First of all, to help with clarity, I'm going to rename the
x
and
y
variables in
main
to be
mx
and
my
. That way there's no ambiguity about what a variable name is referring to.
int main (void) {
int mx=4,my=5;
stuff(&mx,my);
printf("%d %d\n",mx,my);
}
void stuff(int *a,int b){
*a=3;b=2;
morestuff(*a,&b);
}
void morestuff( int x,int *y) {
x=*y;
*y=10;
}
So when
main
calls
stuff(&mx, my)
, the
value of
my
(==5) is passed as the second argument (
b
);
stuff
has no idea where that value came from, no pointer to it, so there's no way that
my
can be changed and
my
will still be 5 at the
printf
.
Now to determine what the value of
mx
will end up as.
stuff
takes a pointer to int as
a
and
main
passes a pointer to
mx
.
The
*a=3;
says to set the value 3 into the location pointed to by
a
.
a
is pointing to
mx
, so this sets
mx
to 3.
But you say
What about "b=2;"?
Remember that the value passed as the
b
parameter is the value 5, not a pointer to where the 5 is stored, so this assignment does not change anything outside of
stuff
. In fact, at this point,
b
behaves
exactly as if it were declared as a local variable to
stuff
. It can be changed locally, but the changes don't
escape from
stuff
.
So what happens when
morestuff
is called?
morestuff
has a value as its first parameter (
x
) and a pointer to int as its second parameter (
y
). The
stuff
passes
&b
(the address of
b
) as
y
. We've already determined that changes to
b
don't escape from
stuff
, so nothing that happens to
y
in
morestuff
can change anything visible outside of
stuff
.
Also, like the
b
parameter to
stuff
, the
x
parameter of
morestuff
is a
value parameter. In this case, the
*a
when
stuff
is calling
morestuff
, is
dereferencing the
a
pointer. It is taking what
a
points to, which is actually
mx
and retrieving its value, which had just been set to 3. Again, as a
value parameter, changes to
x
cannot escape from
morestuff
.
So finally at the end we see that
mx
was set (by
stuff
) to the value 3 and my was left unchanged as the value 5.