Possible Duplicate:
Could anyone explain these undefined behaviors (i = i++ + ++i , i = i++, etc…)
int i = 10;
int n = i++*5*i;
Output
value of n = 550 (in Java) value of n = 500 (in C and C++ )
Why not same result? Why different?
Possible Duplicate:
Could anyone explain these undefined behaviors (i = i++ + ++i , i = i++, etc…)
int i = 10;
int n = i++*5*i;
Output
value of n = 550 (in Java) value of n = 500 (in C and C++ )
Why not same result? Why different?
In Java, this is a well defined operation. It will:
i
(it's now 11);i
(10), because you used the postfix increment operator;i
(50*11 = 550);In both C and C++ this operation has undefined behaviour, so anything could happen. If anything could happen, that explains the results, whatever they are, and whether they make sense to you or not.
In C and C++, operations such as:
j = i++ + i;
are undefined, due to lack of sequence points. In Java, they are well defined. Therefore, you could see a difference in results.
Because what you are doing is undefined. The increment operator should not be placed in expressions of assignment with the variable being incremented.
i = i++; //undefined
n = i++ + i; // also undefined