hey everyone,
Can anyone explain to me why x=4 in the following code?
Code:#include <stdio.h> int main() { int x,y,z; x=2; y=2; x=2*(y++); z=2*(++y); printf("x=%d\ny=%d\nz=%d\n", x,y,z); }
hey everyone,
Can anyone explain to me why x=4 in the following code?
Code:#include <stdio.h> int main() { int x,y,z; x=2; y=2; x=2*(y++); z=2*(++y); printf("x=%d\ny=%d\nz=%d\n", x,y,z); }
Yes - but this should be a simple enough of an exercise to be able to solve yourself.
Try figuring it out and tell us what you think the value of 'x' should be.
Note that there is a distinct difference between "++y" and "y++". The first is a "pre-increment" and the second is a "post-increment".
"Pre-increment" increments the value before it is used in an expression.
"Post-increment" increments the value after it is used in an expression.
Does this help clear up the confusion, or do you need further explanation?
(3.12a)
But in the program you posted, "y++" comes first.since ++y is already 3 before it's used then y++ so y=4
In that case, the current value of 'y' is used before it is incremented.
So on line 11, x = 2 * 2 = 4. Now that the expression is complete, 'y' is incremented to three.
ohh okay so if i understand
x=2*(y++)= 2*2
y=3;
is that the case?
Yes, it seems you have it!
Now analyze line 12 and see if you understand how that result is determined.
okay well since now y=3 and we have ++y which is initialized before it's use y=4 therefor answer is 8
Correct! Well done!
(Note: The terminology in your post should be "incremented" and not "initialized")
You're welcome.