here’s the code which I don’t quite understand:
for(int i = 0; i < (i = 1); i++)
System.out.println("FOR " + i);
I expected this code not to show anything, but instead it outputs ‘FOR’ one time.
I was thinking that i < (i=1) should compare the value of i with the result of the assignment i=1 which is 1 -> so 1<1 which is false -> exit the loop without showing anything.
Maybe the way this comparison is made is different than I understand it. Thank you!
This will be evaluated as: –
On next run, when
i++is executed andibecomes2(Since,iwas1from the(i = 1)assignment on the previous run of loop.)So,
i < (i = 1)evaluates to: –
So, for loop exits.
Note: – In your
condition part (i < (i = 1)), before the assignment (i = 1) happens, the LHS has already been evaluated to be 0, and stored in memory. So, it will remain 0. Its all about the order of evaluation. So the assignmenti = 1will not affect the value of expression on LHS.