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 sta
It's the same as while (true) { /**/ }
... infinite loop until break
or return
or similar occurs.
All it really "does" is look ugly IMO ;)
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 while
s:
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) { ... }
.
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
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