Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
784 views
in Technique[技术] by (71.8m points)

java - Infinite loop application - for(;;)

I am trying to understand the concept behind the for loop example

for (;;)
{
//write code
}

I understand what it does and how it's the same looping structure as while(true), but my question is...is this good programming practice and for what sort of applications would this type of looping structure be applied to?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There are a few situations when this is desired behavior. For example, the games on cartridge-based game consoles typically have no exit condition in their main loop, as there is no operating system for the program to exit to; the loop runs until the console is powered off.

Another example is when a module listen actions from another. It will need to listen all the time, so the listener have to listen for infinite time or until the program turn off. Like Sockets, Threads and UIComponents.

There isn't bad practice on the concept of infinite loop, but if it isn't wanted or prejudice your system's feature it can be considered, like when you create an unintentional infinite loop or lose program control for the loop.

To make the infinite loop a good practice:

  1. Make sure that it is a desired behavior. If it has stop condition, avoid infinite loop!
  2. Make it explicity with for(;;) or while(true). Avoid tautologies in expression, do it simple!
  3. Make it fault tolerant, rescuing expected exceptions and give to them the right treatment!
  4. And the most important! Make a simple infinite loop!

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...