I'm confused in how this code will get executed. Suppose we have
int x=30,*y,*z;
y=&x;
what is the difference between *y++ and ++*y? and also what will be the output of this program?
#include<stdio.h>
int main(){
int x=30,*y,*z;
y=&x;
z=y;
*y++=*z++;
x++;
printf("%d %d %d ",x,y,z);
return 0;
}
The expression x = *y++ is in effects same as:
x = *y;
y = y + 1;
And if expression is just *y++; (without assignment) then its nothing but same as y++;, that is y start pointing to next location after increment.
Second expression ++*y means to increment the value pointed by y that same as: *y = *y + 1; (pointer not incremented)
It will be better clear with answer to your first question:
Suppose your code is:
int x = 30, *y;
int temp;
y = &x;
temp = *y++; //this is same as: temp = *y; y = y + 1;
First *y will be assigned to temp variable; hence temp assigned 30, then value of y increments by one and it start point to next location after location of x (where really no variable is present).
Next case: Suppose your code is:
int x = 30, *y;
int temp;
y = &x;
temp = ++*y; //this is same as *y = *y + 1; temp = *y;
First value of *y increments from 30 to 31 and then 31 is assigned to temp (note: x is now 31).
next part of your question (read comments):
int x = 30, *y, *z;
y = &x; // y ---> x , y points to x
z = y; // z ---> x , z points to x
*y++ = *z++; // *y = *z, y++, z++ , that is
// x = x, y++, z++
x++; // increment x to 31
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With