vidit jain
vidit jain

Reputation: 503

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 looking for answers with references to a variety of sources.

Upvotes: 36

Views: 59021

Answers (6)

VickyP
VickyP

Reputation: 21

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)

Upvotes: 1

Samet Atdag
Samet Atdag

Reputation: 992

It equals to that:

while (true) {
  statements;
}

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

Upvotes: 1

Mephane
Mephane

Reputation: 2022

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;
}

Upvotes: 2

darioo
darioo

Reputation: 47193

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.

Upvotes: 2

RoflcoptrException
RoflcoptrException

Reputation: 52249

In my environment it is like this:

for(;;) { statements; }

endless loop

for(initialisation;condition;updation) { } 

empty loop

Upvotes: 6

Bojan Komazec
Bojan Komazec

Reputation: 9536

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

Upvotes: 47

Related Questions