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

后端 未结 10 1084
迷失自我
迷失自我 2021-01-17 12:59

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         


        
10条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-17 13:50

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

提交回复
热议问题