-
Need help with operators
Hi!
I'm pretty new to c programming (and to programming itself) and I've stumbled upon something I don't really understand about the ++ operator.
Code:
int z, p;
z = 6;
p = z++;
printf("%d %d", z, p); //output: "7 6".
As far as I understand, ++ means add 1, so z++ means z = z+1, which in this case would be z = 6 + 1 = 7.
Now, when I see p = z++, I read it as: p = z = z + 1. Now, since the left value of an equation is assigned the right value, I assume that the new z equals 7 and p equals z, so also 7. However, printf shows p as 6 and not 7. So I really don't understand why p is assigned the old value of z (6) and not the new value (7)?
Can anyone explain? :)
Thanks!
-
Recall that z++ is post-increment, i.e., the increment is only applied after the current value of z is used in the expression. If you use pre-increment instead with ++z, you would then get the behaviour you expected as the increment would be applied before the value is used in the rest of the expression.
-