-3

Moin, I just found a for-loop in some source code.

for (;;) {
    // some work
    if (condition) {
       break;
    }
}

How is this for (;;) working ?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
phisto05
  • 95
  • 4
  • 2
    for till eternity unless god living inside it breaks it – dnit13 Feb 18 '16 at 12:39
  • What did your beginner level C book say when you checked there? – Lundin Feb 18 '16 at 12:39
  • Relevant: [No loop condition in for and while loop](http://stackoverflow.com/questions/13146830/no-loop-condition-in-for-and-while-loop) – Vicente Cunha Feb 18 '16 at 12:42
  • Any or all of the three components of a `for` statement may be left blank. If all are blank, then there is no initialization, no exit test, and no increment section. The behavior follows immediately from that. – Tom Karzes Feb 18 '16 at 13:03

5 Answers5

8

This for(;;) is an infinite loop.

As per C11, chapter §6.8.5.3, The for statement,

The statement
for ( clause-1 ; expression-2 ; expression-3 ) statement
behaves as follows: The expression expression-2 is the controlling expression that is evaluated before each execution of the loop body.[...]

and (emphasis mine)

Both clause-1 and expression-3 can be omitted. An omitted expression-2 is replaced by a nonzero constant.

Also, for the usage of the controlling expression

An iteration statement causes a statement called the loop body to be executed repeatedly until the controlling expression compares equal to 0. [...]

So, in case, all three are removed, the controlling expression is considered as non-zero, which is TRUE forever, thus essentially making it an infinite loop.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
3

It's an infinite loop, like

while (1)

That was mostly used befroe because some compiler complain when they detected an infinite loop with while(1).

The three part of for is optionnal, so if the initialisation part is missing, then there is no initialization, if the test part is missing, it's assume that's true, etc.

Tom's
  • 2,448
  • 10
  • 22
  • thanks, i will accept your answer in a short time. I knew that there is the ;; null expression/statement in c but i thought the test part will evaluate to false if there is none... – phisto05 Feb 18 '16 at 12:46
3
for (;;) {
    // some work
    if (condition) {
       break;
    }
}

is equivalent to

do
{
  //some work
}while(!condition);
niyasc
  • 4,440
  • 1
  • 23
  • 50
1

Read this as "forever". It repeats the block until the condition is met, and the break statement is executed.

Philippe
  • 3,700
  • 1
  • 21
  • 34
1

It is an infinite loop. It means the loop will keep execution until you use break or exit function.

Kyrie
  • 53
  • 7