Reputation: 319
int main()
{
int x = 30, *y, *z;
y = &x;
/* Assume address of x is 500 and integer is 4 byte size */
z = y;
*y++ = *z++;
x++;
printf("x=%d, y=%d, z=%d\n", x, y, z);
return 0;
}
The above is the code.
The output is: x=31, y=504, z=504
Please correct me if I'm wrong:
From what I understand: y=&x;
assigns the address of x
to y
. So, y
now holds the value of 500
.
z=y;
Since y = 500
, this assigns 500
to z
.
What really confuses me is this part *y++=*z++;
, I don't exactly know what this means as there's many things going on at the same time. z
gets incremented and pointed to somewhere (AND where is it pointing actually? There is no address assigned to it like y i.e y=&x;
. Then *y
also gets incremented at the same time (are you even allowed to do that?).
Another thing that confuses me is that: in my opinion, since y
points to x
, when y++
happens, x
should be incremented to 31
, and then when going down the code block x++
happens, x
should now be 32
.
So, question is, how did we get that output of x=31, y=504, z=504
? Thank you.
Upvotes: 0
Views: 621
Reputation: 12837
Let's break it down.
int x=30, *y, *z;
y,z
are defined and x
is initialized.y=&x; z=y;
both of the pointers are assigned with the address of x (i.e. &x
)*y++=*z++;
This one contains a few things, so I'll split it up:postfix++
takes precedence over indirection*
so we can look at *y++
as *(y++)
y++
means that the value of y will be incremented by 1 and since y
is int*
it will actually add sizeof(int)
to it's value [4 in your case]. But the value of the expression y++
is the value of y
before the increment, which leads us to...postfix++
is done, the indirection is evaluated and since y++
's value is the value of "old" y
you get the value of x
Conclusion: y
was incremented by 1
but the indirection (dereference) led us to x.
The same applies to z
. Eventually what happens is that both y,z
are incremented, but before that the value in x is assigned to x (obsolete :) )
Next you'll have x++;
which increments the value of x
by 1. And that's it.
You can think of *y++=*z++;
as:
*y = *z;
y++, z++;
Upvotes: 2