It is left undefined by the C language as to when exactly a post/pre-in/decrement occurs. Thus, statements such as x = x++
are not well formed - avoid them.
+4
A:
Thanatos
2010-07-19 02:22:02
More precisely you aren't allowed to modify a variable more than once in an expression. 6.5/2: *"Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression."*
sth
2010-07-19 02:37:04
Jerry Coffin
2010-07-19 02:41:42
@sth: Even _more precisely_, that's not a limitation on the coder, it's a limitation on the variable itself. Your statement that you "aren't allowed to ..." is not quite correct. You _are_ allowed to, it's just a very silly thing to do :-)
paxdiablo
2010-07-19 02:44:39
Yeah, I was aware that the use of the word "precisely" there would cause some follow-up comments. But it was late at night and I was too lazy to explain what a sequence point is... :)
sth
2010-07-19 14:31:29
A:
When you have:
a = b++;
what is happening is that b is saved to a and after the assigment is done b is incremented by one. So if you do:
x = x ++;
and previously x was 10 what will happen is 10 will be saved to x and after(before your printf is done) x is incremented by one to 11. That's why 11 is printed.
+10
A:
The behaviour is undefined as there is no intervening sequence point in x = x++
, see e.g. the C FAQ.
Georg Fritzsche
2010-07-19 02:25:49
+2
A:
Standards aside (since this is undefined with respect to the standard), the way it ran is the way I would have expected it.
My rule of thumb is that for a line with x++
, you substitute x++
with x
and put x += 1
on the following line (or preceding line for pre-increment).
Following that rule of thumb, your code would be written as
#include <stdio.h>
int main()
{
int x = 10, y = 0;
x = x; // x: 10
x += 1; // x: 11
printf("x: %d\n", x);
y = x; // y: 11
x += 1; // x: 12
printf("y: %d\n", y);
}
Mark Rushakoff
2010-07-19 02:42:13