What does for (;;) mean in Perl?

2020-08-09 09:50发布

问题:

I was looking though a fellow developers code when I saw this ..

for (;;){
   ....
   ....
   ....
}

I have never seen ";;" used in a loop. What does this do exactly?

回答1:

It loops forever. ';;' equates to no start value, no stop condition and no increment condition.

It is equivalent to

while (true)
{
   ...
}

There would usually be a conditional break; statement somewhere in the body of the loop unless it is something like a system idle loop or message pump.



回答2:

All 3 parts are optional. An empty loop initialization and update is a noop. An empty terminating condition is an implicit true. It's essentially the same as

while (true) {
   //...
}

Note that you it doesn't have to be all-or-nothing; you can have some part and not others.

for (init; cond; ) {
  //...
}

for (; cond; update) {
  //...
}

for (init; ; update) {
  //...
}


回答3:

Just like in C, the for loop has three sections:

  • a pre-loop section, which executes before the loop starts.
  • a continuing condition section which, while true, will keep the loop going.
  • a post-iteration section which is executed after each iteration of the loop body.

For example:

for (i = 1, acc = 0; i <= 10; i++)
    acc += i;

will add up the numbers from 1 to 10 inclusive (in C and, assuming you use Perl syntax like $i and braces, in Perl as well).

However, nothing requires that the sections actually contain anything and, if the condition is missing, it's assumed to be true.

So the for(;;) loop basically just means: don't do any loop setup, loop forever (breaks notwithstanding) and don't do any iteration-specific processing. In other words, it's an infinite loop.



回答4:

Infinite loop. A lot of the time it will be used in a thread to do some work.

    boolean exit = false;

    for(;;) {
        if(exit) {
            break;
        }
        // do some work
    }


回答5:

Infinite Loop (until you break out of it).

It's often used in place of:

while(true) { // Do something }


回答6:

It's the same as

while(true) {
   ...
}

It loops forever.

You don't need to specify all of the parts of a for loop. For example the following loop (which contains no body, or update token) will perform a linear search of myArray

for($index = -1; $myArray[++$index] != $target;);


标签: perl loops