I use while true loop in many projects. It serves me well and it's not over-complicated. So, why it is a bad idea to use while true loop infinitely running background processes. Thanks for your answers.
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.
People say it is bad practice to use while (true) , and a lot of the time they are right. If your while statement contains lots of complicated code and it is unclear when you are breaking out of if, then you are left with difficult to maintain code and a simple bug could cause an infinite loop.
The principal complaint about while loops is that they may never end: while (true) { ... } This is the infinite loop. If it ever happens that you construct an infinite loop in code, that code will become non-responsive at run time.
While loop is used to execute a block of code repeatedly until given boolean condition evaluated to False. If we write while True then the loop will run forever.
My project leader doesn't allow this kind of loop in my code, he's arguing that it has to be replaced by
while(!exit_flag)
That's very debatable. while (!exit_flag)
suggests that the loop has a natural exit condition which it will reach at some specific point by itself, e.g. something counting from 0 to 100 and then leaving the loop. However, if you are writing this loop to create a permanent daemon or event loop, then the point of this loop is to keep the program running indefinitely. Nothing says indefinitely better than while (true)
.
There's no real technical difference between both; it's just a matter of readability and expression of intent. Of course, you'll have to square this with the people who will read that code in the end. If their policy is while (!exit_flag)
, so be it.
It is not a bad practice, it just means that you did not think your code through.
The condition is required to tell the loop when to finish looping. If you have a terminating point, then why not put it as a condition?
var i = 0;
while(true){
i++;
if(i == 100)
break;
}
This is fine code. But so is this:
var i = 0;
while(i != 100){
i++;
}
Both methods are correct, but if someone else is reading your code, it is much easier to see when the loop will stop iterating if it is right there in the condition.
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