+ 1

Why is this an infinite loop?

Can't understand what's happening inside the for loop i=i++ . https://code.sololearn.com/cAd55ocePMaD/?ref=app

24th Sep 2019, 1:53 PM
Sunil Kumar Mallah
Sunil Kumar Mallah - avatar
4 Antworten
+ 2
Indeed the variable i is incremented, but this has no effect, because it will be overwritten after increment. This results from the timing of pushing and popping from the stack. Let‘s assume the following code: int i = 1; i = i++; What happens can be evaluated, if you analyze the bytecode (https://en.m.wikipedia.org/wiki/Java_bytecode_instruction_listings) bipush 1 :push 1 on the stack istore_1 :pop 1 from the stack to i iload_1 :push i on the stack (=1) iinc 1 1 :incremented i by 1 istore_1 :pop 1 from stack to i So the variable i is incremented, but subsequently overwritten by the value stored on the stack.
24th Sep 2019, 6:24 PM
Michael
Michael - avatar
+ 1
could use this approach maybe .Just suggestion...for(initializer;limit;increment)
24th Sep 2019, 7:55 PM
LODEKI BRIAN
LODEKI BRIAN - avatar
0
i = i++ will never increment the value of i, because the postfix increment operator returns the original value of i.
24th Sep 2019, 2:06 PM
Michael
Michael - avatar
0
I didn't understand you, i++ will return the original value that's fine. But what about the ++ operator??
24th Sep 2019, 5:30 PM
Sunil Kumar Mallah
Sunil Kumar Mallah - avatar