Best refactoring for the dreaded While (True) loop

When I encounter a while(true) loop, that tells me either

  1. the break condition is not easily tested at the top (or bottom) of the loop,
    • there are multiple break conditions,
    • or the prior programmer was too lazy to factor the loop properly.

1 and 2 means you might as well stick with while(true). (I use for(;;), but that's a style thing in my opinion.) I'm with another poster, why dread this? I dread tortored loops that jump through hoops to get the loop rolled "properly".


Do we really need to refactor while(true) loops? Sometimes it's a coding standard and most of the developers has got used to this structure. If you have to think hard on how to refactor this code, are you sure it's a good idea to refactor it?

Goto used to be a black sheep in coding standards. I've met algorithms where goto made the code much more readable and shorter. Sometimes it doesn't worth to refactor (or better to use goto).

On the other hand you can avoid while(true) most of the time.


What's so dreaded about it? Try finding a common break condition and refactor it to be the head of the loop. If that's not possible – fine.


My preference would be

start:

   // code goes here

goto start;

This most clearly expresses the intent. Good luck getting it past your coding standards. (Wonder how much karma this is going to cost me).