I was working on something in Jetpack recently, and was mind-boggled when I came across a do…while( false ) loop.

Animated What Gif

What confused me so much, is why even use the loop if the condition was always false? Not able to figure out what this bit of code did, I brought the issue up to my team and Dan Walmsley was able to track it down.

Turns out, that in the initial commit, we were using the do...while( false ) loop as something of a poor man’s go-to.

If you look at loop in the initial commit, you’ll see that there are several break statements. So, at any point in time, we could break out of the loop and prevent any other code in the loop being reached. In effect, we would jumping to a spot just out of the loop – hence, goto.

To do while false or not?

While I understand the construct now, it did confuse the hell out of me at first. For that reason alone, I’m not sure it should be used. If you are going to use it, I would suggest at least writing a comment so the next developer has an idea of what’s going on. 😀

Leave a Reply

Your email address will not be published. Required fields are marked *