+ 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
4 Réponses
+ 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.
+ 1
could use this approach maybe .Just suggestion...for(initializer;limit;increment)
0
i = i++ will never increment the value of i, because the postfix increment operator returns the original value of i.
0
I didn't understand you, i++ will return the original value that's fine. But what about the ++ operator??