0

My friend showed me this and I have no idea how it works and what it's called. Can someone explain to me how it loops the way it does? For example:

for(;;){
    cout << "loop" << endl;
}

It will just keep looping the string forever. This kind of loop can be used for anything. How does this work?

smac89
  • 39,374
  • 15
  • 132
  • 179
Adam Bunch
  • 113
  • 1
  • 2
  • 14

5 Answers5

9

According tho the language specification, empty condition in for iteration statament is equivalent to true condition.

6.5.3 The for statement

1 The for statement

for ( for-init-statement conditionopt; expressionopt) statement

is equivalent to

{
  for-init-statement
  while ( condition ) {
    statement
    expression ;
  }
}

...

2 Either or both of the condition and the expression can be omitted. A missing condition makes the implied while clause equivalent to while(true).

So, the loop loops forever. That's all there is to it.

Community
  • 1
  • 1
AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765
0

It loops infinitely as no initialization, conditional and increment values are passed in the parameters of the loop. A typical for loop takes parameters as follows: (<initialization>;<conditional>;<increment>)

hecate
  • 620
  • 1
  • 8
  • 33
0

This post explains it quite well in my opinion. See the answer by spex: Why can the condition of a for-loop be left empty?

With the structure of the for loop being for(clause; expression-2; expression-3){}, when expression-2 is left out it is replaced with a nonzero constant. This is the part of the loop that determines whether it should keep looping or not. As a nonzero constant evaluates to true, it becomes an infinite loop.

Community
  • 1
  • 1
Programmer001
  • 2,240
  • 2
  • 19
  • 35
0

That for loop essentially says the following three things (each separated by the semicolons in your for loop "header?"):

  1. Don't initialize anything.
  2. Don't break from the loop.
  3. Perform no afterthoughts for each loop iteration.

Wikipedia's for loop page actually has a section about this.

jefff
  • 73
  • 1
  • 9
0

As many have pointed out, it is equivalent to while (1).

When is it useful? Wherever you need an infinite loop such as:

  1. A game loop - would be kinda useful to have the game, loop indefinitely until the user decides to quit the game.
  2. OS scheduler - The scheduler needs to loop indefinitely, scheduling processes according to some algorithm until the OS stops
  3. An intepreter - If you have ever programmed in python, you may have come across the interpreter which lets you type some command and then executes it. This is also implemented using a similar infinite loop

In all those examples, the common factor that leads to using an infinite loop is that the terminating condition is not known or the terminating condition is complex (game loops for example)

smac89
  • 39,374
  • 15
  • 132
  • 179