Answer: That's very debatable, while (true) is not a good idea because it makes it hard to maintain this code. But that's not bad since you may not always know the exit condition when you set up the loop or may have multiple exit conditions. However, it does require more care to prevent an infinite loop.
Thanks for your answers. while (true) is not inherently bad practice. Certain uses of while (true) are bad practice, mostly busy-waits where other kinds of waits would be more appropriate, but there's nothing wrong with while (true) itself.
🔹 How to Make an Infinite Loop with While True. We can generate an infinite loop intentionally using while True . In this case, the loop will run indefinitely until the process is stopped by external intervention ( CTRL + C ) or when a break statement is found (you will learn more about break in just a moment).
The while loop will continue as long as the condition is non zero. is also an infinite loop ( because 2 is non zero, and hence true ) . 0 is equal to false, and thus, the loop is not executed.
I wouldn't say it's bad - but equally I would normally at least look for an alternative.
In situations where it's the first thing I write, I almost always at least try to refactor it into something clearer. Sometimes it can't be helped (or the alternative is to have a bool
variable which does nothing meaningful except indicate the end of the loop, less clearly than a break
statement) but it's worth at least trying.
As an example of where it's clearer to use break
than a flag, consider:
while (true)
{
doStuffNeededAtStartOfLoop();
int input = getSomeInput();
if (testCondition(input))
{
break;
}
actOnInput(input);
}
Now let's force it to use a flag:
boolean running = true;
while (running)
{
doStuffNeededAtStartOfLoop();
int input = getSomeInput();
if (testCondition(input))
{
running = false;
}
else
{
actOnInput(input);
}
}
I view the latter as more complicated to read: it's got an extra else
block, the actOnInput
is more indented, and if you're trying to work out what happens when testCondition
returns true
, you need to look carefully through the rest of the block to check that there isn't something after the else
block which would occur whether running
has been set to false
or not.
The break
statement communicates the intent more clearly, and lets the rest of the block get on with what it needs to do without worrying about earlier conditions.
Note that this is exactly the same sort of argument that people have about multiple return statements in a method. For example, if I can work out the result of a method within the first few lines (e.g. because some input is null, or empty, or zero) I find it clearer to return that answer directly than to have a variable to store the result, then a whole block of other code, and finally a return
statement.
AFAIK nothing, really. Teachers are just allergic to goto
, because they heard somewhere it's really bad. Otherwise you would just write:
bool guard = true;
do
{
getInput();
if (something)
guard = false;
} while (guard)
Which is almost the same thing.
Maybe this is cleaner (because all the looping info is contained at the top of the block):
for (bool endLoop = false; !endLoop;)
{
}
Douglas Crockford had a remark about how he wished JavaScript contained a loop
structure:
loop
{
...code...
}
And I don't think Java would be any worse for having a loop
structure either.
There's nothing inherently wrong with while(true)
loops, but there is a tendency for teachers to discourage them. From the teaching perspective, it's very easy to have students create endless loops and not understand why the loop isn't ever escaped.
But what they rarely mention is that all looping mechanisms can be replicated with while(true)
loops.
while( a() )
{
fn();
}
is the same as
loop
{
if ( !a() ) break;
fn();
}
and
do
{
fn();
} while( a() );
is the same as:
loop
{
fn();
if ( !a() ) break;
}
and
for ( a(); b(); c() )
{
fn();
}
is the same as:
a();
loop
{
if ( !b() ) break;
fn();
c();
}
As long as you can set up your loops in a way that works the construct that you choose to use is unimportant. If it happens to fit in a for
loop, use a for
loop.
One last part: keep your loops simple. If there's a lot of functionality that needs to happen on every iteration, put it in a function. You can always optimize it after you've got it working.
Back in 1967, Edgar Dijkstra wrote an article in a trade magazine about why goto should be eliminated from high level languages to improve code quality. A whole programming paradigm called "structured programming" came out of this, though certainly not everyone agrees that goto automatically means bad code.
The crux of structured programming is essentially that the structure of the code should determine its flow rather than having gotos or breaks or continues to determine flow, wherever possible. Similiarly, having multiple entry and exit points to a loop or function are also discouraged in that paradigm.
Obviously this is not the only programming paradigm, but often it can be easily applied to other paradigms like object oriented programming (ala Java).
Your teachers has probably been taught, and is trying to teach your class that we would best avoid "spaghetti code" by making sure our code is structured, and following the implied rules of structured programming.
While there is nothing inherently "wrong" with an implementation that uses break, some consider it significantly easier to read code where the condition for the loop is explicitly specified within the while() condition, and eliminates some possibilities of being overly tricky. There are definitely pitfalls to using a while(true) condition that seem to pop up frequently in code by novice programmers, such as the risk of accidentally creating an infinite loop, or making code that is hard to read or unnecessarily confusing.
Ironically, exception handling is an area where deviation from structured programming will certainly come up and be expected as you get further into programming in Java.
It is also possible your instructor may have expected you to demonstrate your ability to use a particular loop structure or syntax being taught in that chapter or lesson of your text, and while the code you wrote is functionally equivalent, you may not have been demonstrating the particular skill you were supposed to be learning in that lesson.
The ususal Java convention for reading input is:
import java.io.*;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String strLine;
while ((strLine = br.readLine()) != null) {
// do something with the line
}
And the usual C++ convention for reading input is:
#include <iostream>
#include <string>
std::string data;
while(std::readline(std::cin, data)) {
// do something with the line
}
And in C, it's
#include <stdio.h>
char* buffer = NULL;
size_t buffer_size;
size_t size_read;
while( (size_read = getline(&buffer, &buffer_size, stdin)) != -1 ){
// do something with the line
}
free(buffer);
or if you're convinced you know how long the longest line of text in your file is, you can do
#include <stdio.h>
char buffer[BUF_SIZE];
while (fgets(buffer, BUF_SIZE, stdin)) {
//do something with the line
}
If you're testing to see whether your user entered a quit
command, it's easy to extend any of these 3 loop structures. I'll do it in Java for you:
import java.io.*;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line;
while ((line = br.readLine()) != null && !line.equals("quit") ) {
// do something with the line
}
So, while there certainly are cases where break
or goto
is justified, if all you're doing is reading from a file or the console line by line, then you shouldn't need a while (true)
loop to accomplish it -- your programming language has already supplied you with an appropriate idiom for using the input command as the loop condition.
It's not such a terrible thing, but you need to take into consideration other developers when coding. Even in school.
Your fellow developers should be able to see the exit clause for your loop, at the loop declaration. You didn't do that. You hid the exit clause in the middle of the loop, making more work for someone else who comes along and tries to understand your code. This is the same reason that things like "break" are avoided.
That being said, you'll still see things like this in a LOT of code out there in the real world.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With