Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Infinite looping in 'for' and 'while' loops  RSS feed

 
Ravindranath Chowdary
Ranch Hand
Posts: 71
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi friends,
I have question regarding the for loop and while loop.

In the for loop if I do not mention the termination condition it will become an infininte loop.
for (int i=0;;i++){}

In the case of while loop if I mention the expression in the while loop to be true become an infinite loop.
while(true){}

Why this is designed like this?
No condition check in for loop is causing infinite loop and giving of true in the expression value of while is causing infinite loop.

Can anyone please give the reason...

Thanks,
Ravindra.
 
Merrill Higginson
Ranch Hand
Posts: 4864
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In any language, there's always a balance between "safety" (translation: protecting coders from their stupid mistakes) and flexibility. If you overdo the safety, you infringe on flexibility.

While I would probably not use either of the loops you demonstrated, I will argue one point: Neither loop is guaranteed to be infinite. Either could be terminated by using the break keyword inside the loop.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
while(true) and break is a fairly common combination. I'd say I've used it when there are several conditions that could terminate the loop, not just one. Some would say break is a thinly disguised GOTO and should be avoided, but I'm relaxed about that. The idiom is common enough that my old favorite language REXX has a keyword "forever". Your "for" example would be
 
fred rosenberger
lowercase baba
Bartender
Posts: 12542
48
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
sometimes you may want an infinite loop. If you're writing some kind of listener that will run 24 hours a day, why bother a condition?

 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You remembered to put that in a daemon thread, right?
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!