There is nothing wrong withare two common objections to while (true)
: one invalid concern about efficiency, and one legitimate concern about style.
That means that your second objection is invalid, since while (true)
is not a check. In fact, your original version had more conditionals since you had to decide which side to append to after exiting the loop.
As previously mentioned, there is another problem with while (true)
, which is that it keeps the reader in suspense. Most programs are not intended to run in an infinite loop. Therefore, when you see while (true)
, you immediately suspect that something within the loop must eventually cause it to terminate: a break
, a return
, or an exception. Therefore, whenever you feel the urge to write while (true)
, it's always worthwhile to think about whether it is possible to restructure the code such that the termination condition can be expressed in the loop header, rather than buried in the loop body. In many instances, it is possible, but here, I think that my proposal is already optimal.