views:

109

answers:

3

I personally use while(true) for endless loops, but I've seen examples online that use for(;;). Practically speaking, are there any differences between the two, or is it just a stylistic thing?

+1  A: 

Probably just stylistic.

I vaguely remember in the past having a C++ compiler giving me a warning for while(true) but not for for(;;)

Which is probably where the style came from originally.

Joe
+1  A: 

They generate the same IL, so pick whatever you prefer. Having said that endless loops are usually not endless after all, so you might want to express the exit condition as part of the loop.

Brian Rasmussen
The endless loop I wrote is a test method running on a separate thread that raises an event every second. It simulates a server that sends an update every second.
Daniel T.
@DanielT: I guess you rely on the thread being aborted then. You could just as well let the thread exit gracefully.
Brian Rasmussen
+6  A: 

No difference. I checked the IL. I wrote two function as following.

class Program
{
    static void Main(string[] args)
    {
        System.Console.ReadLine();
    }

    static void EndlessWhile()
    {
        while (true)
        {
            Console.WriteLine("Hello");
        }
    }

    static void EndlessFor()
    {
        for (; ; )
        {
            Console.WriteLine("Hello");
        }
    }
}

// IL of both the functions are mentioned below.

.method private hidebysig static void  EndlessWhile() cil managed
{
  // Code size       20 (0x14)
  .maxstack  1
  .locals init ([0] bool CS$4$0000)
  IL_0000:  nop
  IL_0001:  br.s       IL_0010
  IL_0003:  nop
  IL_0004:  ldstr      "Hello"
  IL_0009:  call       void [mscorlib]System.Console::WriteLine(string)
  IL_000e:  nop
  IL_000f:  nop
  IL_0010:  ldc.i4.1
  IL_0011:  stloc.0
  IL_0012:  br.s       IL_0003
} // end of method Program::EndlessWhile

.method private hidebysig static void  EndlessFor() cil managed
{
  // Code size       20 (0x14)
  .maxstack  1
  .locals init ([0] bool CS$4$0000)
  IL_0000:  nop
  IL_0001:  br.s       IL_0010
  IL_0003:  nop
  IL_0004:  ldstr      "Hello"
  IL_0009:  call       void [mscorlib]System.Console::WriteLine(string)
  IL_000e:  nop
  IL_000f:  nop
  IL_0010:  ldc.i4.1
  IL_0011:  stloc.0
  IL_0012:  br.s       IL_0003
} // end of method Program::EndlessFor
this. __curious_geek
Nice, thanks! :)
Daniel T.