Consider this simple code:
// E1
public void doTest(String pattern) {
int counter = 0;
while (counter < 3) {
counter = counter++;
}
System.out.println("Done");
}
This causes an infinite loop.
However if the statement that increments the counter is written like this:
E2. counter = ++counter;
or this
E3. counter++;
It terminates normally. I understand that the incrementing occurs after the assignment in the version that fails which explains why E2 works, but I thought java assigned the results of an increment in the variable that is incremented as in E3. So I'm perplexed as to why E1 fails but E3 does not.
An infinite loop is a loop that keeps running 'forever' (e.g., Liberty & MacDonald, 2009; Wikipedia, 2019). These loops don't exit like regular C# loops do, but instead use up computer resources and freeze our application. Most infinite loops are caused by either a coding or logic mistake.
A loop becomes infinite loop if a condition never becomes FALSE. You must use caution when using while loops because of the possibility that this condition never resolves to a FALSE value. This results in a loop that never ends. Such a loop is called an infinite loop.
A loop becomes infinite loop if a condition never becomes false.
counter = counter++;
The above code has no effect on counter
. It is effectively same as:
int temp = counter;
counter++;
counter = temp;
So, the value of counter
is not changing at all.
On the other hand, if you use:
counter = ++counter;
The counter is incremented first, and then is re-assigned to counter. Essentially, you can simply ignore the assignment part, and keep it simply this:
counter++; // Or ++counter
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With