C Programming - Pointers - Discussion
Discussion Forum : Pointers - Find Output of Program (Q.No. 3)
3.
What will be the output of the program ?
#include<stdio.h>
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;
}
Discussion:
92 comments Page 10 of 10.
Sahibpreet Singh said:
2 years ago
*(value of address) and increment/decrement operators lie in the same level of precedence. Their precedence level proceeds in right to left manner.
So, if ++ is to the left of * then * will be evaluated first.
Similarly, (in this case) ++ is to the right of * so y++ is evaluated first. *y++ is same as *(y++) and ++*y is same as ++(*y).
So, if ++ is to the left of * then * will be evaluated first.
Similarly, (in this case) ++ is to the right of * so y++ is evaluated first. *y++ is same as *(y++) and ++*y is same as ++(*y).
(8)
Ramanathan said:
1 year ago
@All.
Here y and z point to the same location and that contains the address of var x and dereferences to value 30.
Then post increment ++ has higher precedence than * this the address of y gets incremented but still. Not assigned to ptr var y as it's post decrement. The updated address is shown only while printing it at the final statement so the address remains the same now similar concept applies to *z++ thus no changes happen inside this statement next x gets incremented this at the final statement we get the incremented value of x i e 31 and the updated address of y and z i.e the postfix operation has come into light only after its use after post increment line.
i.e
Say int x=30 now if I printf("%d",x++);
I still get 30 as it isn't assigned (incremented value ) to var x. It is only after this block finishes execution.
Now again printf("%d",x) and you get the incremented value i.e 31.
Here y and z point to the same location and that contains the address of var x and dereferences to value 30.
Then post increment ++ has higher precedence than * this the address of y gets incremented but still. Not assigned to ptr var y as it's post decrement. The updated address is shown only while printing it at the final statement so the address remains the same now similar concept applies to *z++ thus no changes happen inside this statement next x gets incremented this at the final statement we get the incremented value of x i e 31 and the updated address of y and z i.e the postfix operation has come into light only after its use after post increment line.
i.e
Say int x=30 now if I printf("%d",x++);
I still get 30 as it isn't assigned (incremented value ) to var x. It is only after this block finishes execution.
Now again printf("%d",x) and you get the incremented value i.e 31.
(1)
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers