Re: question on calculating
The post fix ++ increments the variable AFTER the variable's current value has been used in the expression.
i += i++; // add value of i to i then incr i by one
As you can see this is very confusing. Anyone that codes this way should be fired for writing confusing code.
Re: question on calculating
Hi,
thanks for your reply. I am still confused though.
the value of i before the confusing expression is 6.
So I would expect something then like
i += i
i = 6+6
=12
then the increment =13.
But it's not, the return value is 12.
Re: question on calculating
Yes its confusing. There is a timing of when this part happens and when that part happens.
If you want to see the order of the steps, have the compiler output the code it generates. I forget the option.
Re: question on calculating
If you are unsure of the order of operations, use parenthesis to clarify what it is you intend to have happen.
The best solution is to only use the ++/-- operators in the pre-fix notation, and to make sure that you don't force the compiler to have to use order of operations rules with these operators.
Technically it doesn't matter pre-fix or post-fix if you use it in this fashion, but it's a good habit to use pre-fix because in other languages (for example, C/C++) there is the potential for differences in performance between using the pre-fix or post-fix notations (when the user decides they want to overload the ++/-- operators, but this is out of the scope of Java programming).
So, for example in your above code:
Code Java:
int i=5;
++i;
if (i == 5 || false){
System.out.println("before: "+i);
i += i;
++i;
}
System.out.println(i);
There is zero ambiguity here and it is very clear what is happening (it'll print out 6, then 13).
The only way to know for sure what the program is doing is to look at the disassemble of the program. Likely what's happening is that i++ is writing 7 into the memory location where i is. However, when the += gets evaluated, it's using the value of 6 for i and i++, and then writes the result 12 into that same memory location, nuking any changes made by i++.
Re: question on calculating
Well, the point is not how to make it better, as this was an exam question.
Seeing the answers now, I feel it's a bit unfair to ask that in a MC test. Ah well...thank you very much for the explanation helloworld922.