开发者

What does the term "empty loop" refer to exactly in C and C++?

Is it this kind of thing:

for(;;)
 {
   statements;
 }

Or is it this:

for(initialisation;condition;updation)
{
}

I am looki开发者_C百科ng for answers with references to a variety of sources.


Your first case (for with empty expressions) is an infinite loop and the second one (with empty body of the for statement) is an empty loop


In my environment it is like this:

for(;;) { statements; }

endless loop

for(initialisation;condition;updation) { } 

empty loop


Answer is context dependent.

If you mean an empty for loop, then

 for(;;)
 {
     statements;
 }

is such a thing.

Although, the same thing can be achieved with a while loop:

while(true)
{
    statements;
}

and this isn't an "empty" loop. Both of these are infinite loops that you must break out of using break inside of your loop.

On the other hand,

for(initialisation;condition;updation)
{
}

this is an "empty" loop that bascially does nothing, except perhaps update some variables that could be defined before the loop itself.


An empty loop is a loop which has an empty body, e.g.

for(int i = 0; i < 10; ++i) {}
while(cin) {}

(note that the second example here also happens to be endless)

There are cases where these are useful, for example when a function has a desired side-effect and returns its success, and should repeated until unsuccessful, for example to read the last line in a file:

std::string getLastLine(std::string filename)
{
  std::ifstream in(filename.c_str());
  if(!in)
    return "";

  std::string line;
  while(std::getline(in, line)); // empty loop, the operation returns the condition
  return line;
}


It equals to that:

while (true) {
  statements;
}

Infinite for loop is a loop that works until something else stops it.


for(;;)
 {
   statements;
 }

is endless loop because there is redundant value/Grabage value which makes the loop true

for(initialisation;condition;updation)
 {
   body;
 }

is just syntax for for loop (educational purpose use)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜