2

I was looking through some code at work and found something I've not encountered before:

for (; ;)
{
   // Some code here
   break;
}

We call the function that contains this all the time, I only recently got in there to see how it works. Why does this work and is it documented somewhere?

It seems as though a while loop would have been more appropriate in this instance...

Jeremy Harris
  • 24,318
  • 13
  • 79
  • 133

3 Answers3

7

It's essentially the same as while(true). It doesn't have any initialisation, doesn't change anything between iterations, and in the absence of anything to make it false the condition is assumed to be true.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • So the question is if this behaviour is specific to the for-loop or if any empty statement is consideret to be true... – mensi Sep 18 '12 at 18:09
  • Oh PHP, you have nothing so you assume an infinite loop is more desirable than no code execution. PHP can be such a little tricky bastard to debug sometimes. – thatidiotguy Sep 18 '12 at 18:10
  • `if()` gives a parse error on the unexpected `)`. Only the `for` loop actually has three statements in the parentheses, each delimited by `;`. – Niet the Dark Absol Sep 18 '12 at 18:10
  • 2
    @thatidiotguy: well, you can do the same thing in C or C++, this is definitely not a PHP thing – nico Sep 18 '12 at 18:11
  • @nico Haha I see that you are correct even in the Java code I am writing right now. At least the IDE I am using gives a warning about unreachable code though. sheez. I guess I am overly scarred from PHP's type conversion system. – thatidiotguy Sep 18 '12 at 18:13
3

It's an infinite loop.

Normally you would have something like:

for ($i=0; $i<10; $i=$i+1)

But you can omit any of the parts.

These are all valid:

for ($i=0; ; $i=$i+1)
for (; $i<10; $i=$i+1)
for (; $i<10;)

However, if you omit the second part, there will be no condition for exiting the loop. This can be used if you do not know how many times you want to run the loop. You can use a break instruction to exit the loop in that case

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

Note that if you do not put a break the page will just get stuck and run indefinitely

nico
  • 50,859
  • 17
  • 87
  • 112
1

The first blank statement is executed at the beginning.

The second blank expression (which determines whether you exit the loop or not) evaluates to TRUE implicitly:

http://php.net/manual/en/control-structures.for.php

The third blank statement executes after each iteration.

So any condition that kicks out of the loop will need to be in the loop itself.

John
  • 15,990
  • 10
  • 70
  • 110