2

I'm a relatively new programmer and many a times I have seen expert programmers writing a piece of code under the expression

while True

I am confused what significance does it make? Is it used to execute that part of code which is necessary to be executed or is it just a convention?

James Cronen
  • 5,715
  • 2
  • 32
  • 52
kartikeykant18
  • 1,737
  • 6
  • 28
  • 42
  • 1
    This should answer your question: http://stackoverflow.com/questions/6850380/are-whiletrue-loops-so-bad – Will Jan 24 '14 at 13:53
  • possible duplicate of [is while(true) bad programming practice?](http://stackoverflow.com/questions/390481/is-whiletrue-bad-programming-practice) – Jakub Kotowski Jan 24 '14 at 13:55
  • @jkbkot It's slightly different IMO. The one you linked to is comparing and contrasting with `while (condition)` whereas this one is asking more broadly. (Although if the OP meant "as opposed to `while (condition)` then I suppose it is a duplicate after all.) – starsplusplus Jan 24 '14 at 14:11
  • @starsplusplus true, I was thinking about it too. I linked it because some of the answers and comments address the OP's point too - e.g. the use of while (true) in multitrheading, etc. – Jakub Kotowski Jan 24 '14 at 14:14
  • Yes, the OP might well find it useful/interesting. :) – starsplusplus Jan 24 '14 at 14:19

2 Answers2

4

In some cases it is desirable, for the condition to always evaluate to true, creating an infinite loop.

while(true)
{
    //do your work here in loop
}

When such a loop is created intentionally, there is usually another control structure (such as a break statement) that controls termination of the loop. For example:

while (true) 
{
   //do complicated stuff
   if (someCondition) break;
   //more stuff
}
anj
  • 162
  • 2
  • 7
0

That means infinite loop. So if you want to use this, you have to put a code inside, to get out of this loop (break, return), otherwise your code will be in this loop forever.. Check:this

Community
  • 1
  • 1