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

后端 未结 10 1183
迷失自我
迷失自我 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:52

    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

提交回复
热议问题