I’m doing some research about Java and find this very confusing:
for (int i = 0; i < 10; i = i++) {
System.err.print("hoo... ");
}
This is never ending loop!
Anybody has good explanation why such thing happens?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The above loop is essentially the same as: –
the 3rd part of your
forstatement –i = i++, is evaluated as: –You need to remove the assignment from there, to make it work: –
(On OP request from Comments)
Behaviour of
x = 1; x = x++ + x++;: –As far as your issue as specified in the comment is concerned, the result of the following expression: –
is obtained as follows: –
Let’s mark different parts of the second statement: –
Now, first the RHS part
(A + B)will be evaluated, and then the final result will be assignmed tox. So, let’s move ahead.First
Ais evaluated: –Now, since the assignment of
AtoRis not done here, the 3rd step is not performed.Now, move to
Bevaluation: –Now, to get the value of
x++ + x++, we need to do the last assignment that we left in the evaluation ofAandB, because now is the value being assigned inx. For that, we need to replace: –So,
x = x++ + x++, becomes: –Break up of 3rd part of
x = x++, to see how it works inx = x++ + x++case: –Wonder why the replacement is done as
A --> old1and notx --> old1, as in case ofx = x++.Take a deep look at
x = x++part, specially the last assignment: –if you consider
x++to beAhere, then the above assignment can be broken into these steps: –Now, for the current problem, it is same as: –
I hope that makes it clear.