-
IMHO it should be 7 and C does the right thing, but now I hear from C gurus that it's undefined.
I wonder what Limbo does...
-
On my Mac:
ddas-computer:~ dda$ more nasty.c
/* nasty.c */
main()
{
int x = 3;
x += x++; /* na-yasty! */
printf("x is %d\n", x);
}
ddas-computer:~ dda$ ./nasty
x is 4
?!?!?!?
-
In C, the expression x += x++ is undefined. You are not allowed to modify a variable more than once in a single expression. Some C compilers will return 7 and some will return 6 and others will return other values. Also, the amount of optimization requested may effect the result.
I don't know what C# will do with this (or Java for that matter).
Don't ya just love C :-)
-
I'm not sure how you can get 7. The expected answer is 6 and if it were x += ++x, then I'd expect 8.
-
No, I would think the expected answer is 7.
int x = 3;
x += x++;
x is 3. x++ is a post-increment, so we evaluate first. x += 3 is 6. Then the ++ kicks in, making it 7.
Of course, this is all rather confusing, which is probably one of the reasons why it's undefined...
-
Consider the following machine instructions. ("load x, y" load the value of y into x; R0-R2 are registers; @a and @b are arbitrary memory locations).
All three of the following instruction sequences correctly implement y += x++ when x and y are different addresses. However, whenn x and y are the same address (as in x += x++), then you get the following results.
A: 4
B: 6
C: 7
Here are the sequences ...
A = code {
load R0, @b
inc R0
load R1, @a
add R1, @b
load @a, R1
load @b, R0
}
B = code {
load R0, @b
inc R0
load R1, @a
add R1, @b
load @b, R0
load @a, R1
}
C = code {
load R0, @b
load R1, R0
inc R1
load @b, R1
load R1, @a
add R1, R0
load @a, R1
}
-
I would've expected 7, but for a slightly different reason:
x = 3;
x += x++;
The RHS of the statement is evaluated first, including side effects: so we get the partially evaluated statement (x += 3), but x has been incremented to 4 by the ++ operator. So when the += operation is performed, x becomes 7.
-
If you follow the link and read the section on postfix increment and decrement (8.1.7) you will see that for limbo the result is undefined if the same object is changed more than once in the same expression. Which is the same rule that applies to C but not Java.