12

I found an empty for statement in an existing bit of code and I'm wondering what it does and is it "safe". It just feels wrong.

for(;;)
{
   //some if statements and a case statement
}

Thanks!

Beth Lang
  • 1,889
  • 17
  • 38
  • Thanks everyone. There is a break and in this case it is a case of the code needing to be changed for better readability. – Beth Lang Oct 08 '10 at 18:13
  • If you got the answer you wanted, you should click the checkmark next to it to reward the author. :) – Sasha Chedygov Oct 08 '10 at 18:14
  • See http://stackoverflow.com/questions/2888558/java-what-is-for/2888580#2888580 for an explanation. It works the exact same way in Java, C++ and C#. And here's my rationale for preferring this over `while(true)`: http://stackoverflow.com/questions/2611246/is-for-faster-than-while-true-if-not-why-do-people-use-it/2611529#2611529 – jalf Oct 08 '10 at 18:16
  • @jalf: Even after 17 minutes, I'd say there's a pretty good selection of answers here... – Sasha Chedygov Oct 08 '10 at 18:19
  • @musicfreak: yes, but why the rush? I'm all for reminding people to accept answers if it seems like they've forgotten to do so, but I doubt that's the case here. And you might just give a new user the impression that they're *supposed* to accept an answer almost instantly. – jalf Oct 08 '10 at 18:32
  • @jalf: Well to be honest, I didn't realize how new the question was when I posted that. So my mistake, but I don't think it's a big deal. I would have accepted the answer after 10 minutes in this case as well, because it was clearly the correct answer. – Sasha Chedygov Oct 08 '10 at 18:51
  • wow i didnt know this would compile, interesting. equivalent of while(true){} – Brady Moritz Oct 08 '10 at 20:23

10 Answers10

17

This is one way of creating an infinite loop. It's a regular for loop, but with empty initialization, condition, and increment expressions. Because the condition expression is a no-op, the loop never exits. It's perfectly "safe" assuming it has a terminating condition (a break or return statement [or even a goto, I suppose]) somewhere.

Personally, I prefer to write infinite loops with whiles:

while (true) 
{  
    //some statements and a case statement
}

(because for is for iteration and while is for repetition).

However, after reading this question (linked by @jailf), I now prefer while (42) { ... }.

Community
  • 1
  • 1
Seth
  • 45,033
  • 10
  • 85
  • 120
  • 6
    I consider `for(;;)` more readable. :) If there is no condition for my loop, why should I write one (such as `true`)? ( `for(;;)` explicitly tells the reader "there is no terminating condition for this loop", which I consider as readable as it gets. – jalf Oct 08 '10 at 18:18
  • 5
    It is an interesting bit of trivia to ask students and novices if a totally empty boolean expression is true or false. Most of us would consider "empty" to be most analogous to 0/false. But C considers empty to be true, as shown by this expression. – abelenky Oct 08 '10 at 18:45
  • 1
    @abelenky: C# doesn't consider empty to be true: there's no such thing as an empty boolean expression in C#. The spec special-cases the situation where the `for` condition is missing, so there'll *either* be a valid boolean expression *or* nothing - two distinct scenarios. – LukeH Oct 08 '10 at 23:12
  • 1
    @abelenky: C doesn't consider empty to be true as can be shown by trying `while()` – Ramon Marco L. Navarro Oct 14 '10 at 04:36
5

It's equivalent as having an infinite loop:

while (true) {

}

It's safe. You need to provide an external exit mechanism though. I.E., with a break within the for loop.

Pablo Santa Cruz
  • 176,835
  • 32
  • 241
  • 292
4

This is a common idiom for an indefinite or infinite loop. You purposely might have an indefinite loop if you are looking for a condition that is not finite at the beginning -- such as user input or the end of a file of unknown size. You might also see while(1) or while(true) for the same thing. It says 'do this thing { whatever } until there is no more...'

Inside that loop structure is probably a conditional and a break statement, such as:

for(;;)
{
    Console.Write("Enter your selection (1, 2, or 3): ");
    string s = Console.ReadLine();
    int n = Int32.Parse(s);

    switch (n)
    {
        case 1:
           Console.WriteLine("Current value is {0}", 1);
           break;
        case 2:
           Console.WriteLine("Current value is {0}", 2);
           break;
        case 3:
            Console.WriteLine("Current value is {0}", 3);
            break;
        default:
           Console.WriteLine("Sorry, invalid selection.");
           break;
        }
    if(n==1 || n==2 || n==3)
        break; // out of the for(;;) loop    

 }

The key whether is it "safe" or not is to figure out the logic of how you leave that loop, or your indefinite loop will become an unintended infinite loop and a bug.

More at the C# site for for: HERE

dawg
  • 98,345
  • 23
  • 131
  • 206
3

All of the expressions of the for statement are optional; for example, the following statement is used to write an infinite loop:

> for (; ; ) {
>     // ... }

Taken from MSDN

npinti
  • 51,780
  • 5
  • 72
  • 96
3

It's the same as while (true) { /**/ } ... infinite loop until break or return or similar occurs.

All it really "does" is look ugly IMO ;)

Dagg Nabbit
  • 75,346
  • 19
  • 113
  • 141
3

This has been asked multiple times on SO. The best discussion on the topic is at the following link:

Is "for(;;)" faster than "while (TRUE)"? If not, why do people use it?

Community
  • 1
  • 1
Michael
  • 3,821
  • 2
  • 19
  • 18
2

It's valid syntax for an infinite loop. You need to "break;" out of it. This was popular back in the C++ days IIRC.

As far as being safe, you're right in feeling "wrong" about this. Usually there would be an "if" condition inside where you would decide if you continue or break the loop. If you don't verify all execution paths it could very well lead to an infinite loop. I would try and do this some other way.

enriquein
  • 1,048
  • 1
  • 12
  • 28
2

It's sometimes called a "forever" loop, because that's what it does. Look for either a break; or return; statement inside the loop or for the loop to be wrapped in a try/catch block. Personally, I try avoid that kind of thing.

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
1

Were there any break, return, or throw statements? That‘s the only way out. Is it safe? It depends if you feel safe inside an infinite loop. Some applications need one.

Josh Lee
  • 171,072
  • 38
  • 269
  • 275
1

This is very common on embedded systems without an operating system. If your program terminates, there is no underlying system to handel that. So mostly there's one huge infinite loop in which most of the operations are handled.

Juri Robl
  • 5,614
  • 2
  • 29
  • 46