ActionScript 3.0: A better while loop

The while loop is one of the basic looping structures in any programming language. It performs admirably, but how many times have you been bitten because you forgot to increment your counter? Chances are it's happened more than once; it's ok, it happens to all of us...but not anymore.

I was looking over some code at work this week and I came up with an idea on how to avoid infinite loops. Let's take a look at a standard while loop:

var count:int = 0;
while(count < 1000)
{
    // do stuff
    count++;
}

That's it; nothing special, right? In my eight years of software development, that's pretty much the only way I've seen people write a while loop. However, there is a better way. If you forget to increment the counter, your program will hang - caught in an infinite loop. That's bad business. Below is the way I've started writing my loops.

var count:int = -1;
while(++count < 1000)
{
    // do stuff
}

BOOM! How 'bout that? I can't stress enough how big of a fan I am of this new style for while loops! The habit is easy to get into and completely avoids the possibility of forgetting your increment statement. I know a lot of you out there may have already been doing this, but many others are probably not so I hope this helps some of you out.

Spread the word and let's make this the new standard for while loops!

Bookmark and Share

4 Responses to “ActionScript 3.0: A better while loop”

  1. AlecT says:

    I’m going to start doing this. I HATE forgetting to update my counters!!

  2. Aristo says:

    Yeah – thats looks sweet, haven’t tested it yet.

    I’ve heard bit shifting is the fastest thing there is – could you set up a bit shift operation >>
    ??

    Hmmm…

  3. penny says:

    Excellent site you have here but I was wanting to know if you knew of any discussion boards that cover the same topics talked about in this article? I’d really like to be a part of group where I can get feedback from other knowledgeable people that share the same interest. If you have any suggestions, please let me know. Thank you!

  4. Rhuno says:

    I started a thread on this at ActionScript.org. You can check it out here if you’d like:

    http://www.actionscript.org/forums/showthread.php3?t=260012

Leave a Reply

Subscribe to RSS feed FGS5 Badge