views:

142

answers:

4
+4  A: 

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.

Thanatos
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
Jerry Coffin
@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
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
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
Thanks! I was not previously aware of sequence points.
danben
+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