Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C# is a for(;;) safe and what does it really do?

Tags:

c#

.net

for-loop

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!

like image 944
Beth Lang Avatar asked Oct 08 '10 18:10

Beth Lang


2 Answers

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) { ... }.

like image 162
Seth Avatar answered Oct 15 '22 17:10

Seth


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.

like image 21
Pablo Santa Cruz Avatar answered Oct 15 '22 17:10

Pablo Santa Cruz