Curious about while(true){}

I'm curious about using a while statement with a truecondition. What is the advantage of using a while(true) statement with break to exit the while statement over something like a for loop? I guess I'm just curious when a good time to use this technique would be? I saw it demonstrated in a quick sort algorithm at school today and was just curious about it. Insight?

Edit: In my Java course we were taught that using break was a bad habit. Seems like this code violates something or is it acceptable to use break often in C++.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
using namespace std;

int main (int argc, char * const argv[]) {
	
	int counter = 9;
	
	while (true) {
		
		cout << "Counter: " << counter << endl;;
		counter--;
		
		if (counter == 0) {
			break;
		}
		
	}
	
    return 0;
}

Last edited on
My old tutor said to me a good example use for the while true loop would be like a dvd, vcr etc units infra red receiver. He told me they are technically always in this state waiting for a message to be sent from the remote. I don't know if this is true or not but I'm not a fan of them myself.

I think when using a while / do while you should always have some sort of condition to break from it. But this is just my personal thoughts on it.
Unless it's something like what Mythios mentioned (endless loop for message processing), I personally think using while (true) is very sticky unless you are guaranteed that a condition will be met to break out of the loop.

For something that doesn't need a near-endless loop, it really would be better to use a for loop...even if you set it to loop 100,000 times or a 1,000,000 times, I think it's safer than accidentally being stuck inside an endless loop. Just my silly opinion though...
Most hardware devices use Hardware interrupts as opposed to polling. The program defines an Interrupt Service Routine (ISR), and when the hardware receives an interrupt (such as receiving a remote signal), it halts the program and calls the ISR. The ISR processes the interrupt then passes control back to the main program right where it was previously halted.

I've seen while(true) used because the looped code had multiple break locations, but that is generally a bad practice (in the same way that multiple returns from a function is bad practice).

I've also seen while(true) used because the looped code had multiple exit conditions (just as bad a practice). I had to work with some old C code once that had over a dozen separate exit conditions scattered through several hundred lines of code (with function calls to several thousand lines of additional code) inside a while(true). It was an old OCRA/OCRB algorithm we wanted to bring into our newer product for legacy support. Ironically, the algorithm had a history of intermittently locking up, and most of those exit conditions were attempts to prevent that, with limited success.
I think when using a while / do while you should always have some sort of condition to break from it. But this is just my personal thoughts on it.

I agree with that statement but only if a logical condition is available. I don't see anything wrong with using the while true loop as long as you are going to write code that won't send it into an infinite loop. Then again perhaps I haven't written a large enough program for me to fully know...
For something that doesn't need a near-endless loop, it really would be better to use a for loop...even if you set it to loop 100,000 times or a 1,000,000 times, I think it's safer than accidentally being stuck inside an endless loop.
Because there's nothing like breaking a procedure that's going well just because it's taking a bit long.
Except under user demand, code shouldn't be made to break prematurely on the assumption that you made a mistake and it's non-halting.

I've often had to while (1) because I had to break in the middle of the loop, the alternative being repeated code.
It's also not unusual for the condition to not be easily written in a single expression. You might need to make a couple calls before really knowing whether the loop should continue.
Last edited on
It's OK to use break but there's no good reason to create an infinite loop and escape by means of break; that is definitely bad programming when you could just use a condition. If there are extenuating circumstances (need to escape the loop in the middle or something) then it would be reasonable.
An infinite loop is one that could actually go on to infinity (in theory). A while (1){/*...*/} is not necessarily an infinite loop.

I disagree. I prefer making a slightly more complex while (1) than repeating code or moving the condition code to a different function.
I prefer approach A.
A)
1
2
3
4
5
6
while (1){
    //(complex condition)
    if (/*break loop*/)
        break;
    //...
}

B)
1
2
3
4
5
//(complex condition)
while (!/*break loop*/){
    //...
    //(complex condition)
}

C)
1
2
3
4
5
6
7
static bool f(/*...*/){
    //(complex condition)
}
//...
while (f(/*...*/)){
    //...
}

C is my runner-up, but it has the problem that maintaining the condition may involve maintaining the parameters to the function, and that you may putting something in a different hierarchy when it belongs in the same one. It really has to be evaluated on a case by case basis.

As far as programming practices go, you can do a lot worse than a mere while (1):
1
2
3
4
5
6
7
while (1){ //label:
    //...
    if (foobar)
        continue; //goto label;
    //...
    break;
}

1
2
3
4
5
6
do{
    //...
    if (foobar)
        break; //(continue also works)
    //...
}while (0);
Last edited on
True enough (as in the last example) but only if your condition is really convoluted would you need to resort to break in most cases (unless, as noted in my last post, there were extenuating circumstances). The point of those brackets where you put the true is to insert a condition to end the loop.
jRaskell wrote:
(in the same way that multiple returns from a function is bad practice).


What? Who told you that? >_>
The point of those brackets where you put the true is to insert a condition to end the loop.
Not necessarily. Programming has rules, but they don't extend to style. Who says I need to put a valid condition there? I could as well put something I want to execute at every loop:
while (++a){/*...*/}
Who says I have to put an increment or decrement as the third for parameter?
for (int a=0;a<30;){/*...*/}
Or that the condition needs to be related to the declared variable?
for (int a=0;foobar;){/*...*/}

These are all perfectly valid constructions, and none of them are bad practice.

EDIT: Oh, I didn't see that. Clearly a former Pascal programmer.
Real programmers disdain structured programming. Structured programming is for compulsive, prematurely toilet-trained neurotics who wear neckties and carefully line up sharpened pencils on an otherwise uncluttered desk.
Last edited on
That may be true but it's the usual style. Break is, in my opinion, only to be used where necessary, and those are not situations where it's necessary. Better to be placed in the loop's code block.
Opinion on break, as has been shown in other threads, is varied but that's my general opinion.
See, I think your problem is that you're confusing break with some sot of last resort, or a failsafe mechanism, like those big red buttons next to dangerous machinery.
It's not. It's just another control flow statement like if or while, except this one happens to behave like a structured goto. You can use it or not use it, but you can't say it's bad practice to use it just because you don't like it. That privilege is left to computer scientists like Dijkstra.
Thanks for your responses I appreciate it.

My old tutor said to me a good example use for the while true loop would be like a dvd, vcr etc units infra red receiver. He told me they are technically always in this state waiting for a message to be sent from the remote.
Most hardware devices use Hardware interrupts as opposed to polling. The program defines an Interrupt Service Routine (ISR), and when the hardware receives an interrupt (such as receiving a remote signal), it halts the program and calls the ISR. The ISR processes the interrupt then passes control back to the main program right where it was previously halted.


So a Blu Ray player is constantly "listening" with a while(true){//break;} loop and upon receiving an interrupt breaks?
1
2
3
4
5
6
while (true){
    
    if (interrupt)
        break;
 
}


How might the code for an Interrupt Service Routine look? How would it go about passing control back to the "listening" while statement?
Topic archived. No new replies allowed.