You are here

Implications When Executing Loops

5 February, 2015 - 11:20

If a programmer sets up a counting loop incorrectly, usually one of three things happen:

  • Infinite loop usually caused by missing update attribute.
  • Loop never executes usually the text expression is wrong with the direction of the less than or greater than relationship needing to be switched.
  • Loop executes more times than desired update not properly handled. Usually the direction of counting (increment or decrement) need to be switched.

Let's give an example of the loop executing for what appears to be for infnity (the third item on our list).

Example 15.4: C++ source code

for (int x = 0; x  <  l0; x--) { cout «  x «  endl; } 

The above code accidently decrements and the value of x goes in a negative way towards -2147483648 (the largest negative value in a normal four byte signed integer data type). It might take a while (thus it might appear to be in an Infinite loop) for it to reach the negative 2 billion plus value, before fnally decrementing to positive 2147483647 which would, incidentally, stop the loop execution.