Wednesday, February 27, 2013

Infinite Loops


As we’ve discussed, loops are a powerful control structure designed to allow you to repeat a certain task until whatever you wanted to do is accomplished (all of your numbers are added together, all of your strings are lower case, etc). We are working on a few basic assumptions here:

  • The task we are trying to accomplish is finite
  • Every iteration brings us closer to the end
  • We can know when we are done


This is why every loop has a condition that tells us when we are done with the loop, and why a for loop intrinsically has a counter variable to make it easy to tell where you currently are.

Why is that important?

When you write a computer program it does exactly what the instructions you gave it make it do. Not what you intended for it to do, not what you think the instructions you gave it should do. It does exactly what they say to do. Let’s look at one of my classically obtuse examples.

 

What this programmer probably meant to have happen here was for the loop to repeat until i is ten and then finish. A small, but important, piece is missing: incrementing i. Instead of printing out the number 1 through 9, it will print out 1 infinite times (or rather, until your computer crashes).

The piece of our loop structure that we missed is that every iteration of the loop leaves us where we were before. If any of our loops assumptions are missing or incorrect, we will probably run into an infinite loop like this one. Most often an infinite loop is the result of programmer error.


Why should you care?

Even though I brought up an example here, you will probably make a similar mistake at least a couple times before you really understand infinite loops. However, knowing what they are and why they happen will help you spot them and correct them much more quickly.


No comments:

Post a Comment