Blog Post · For(;;) a While(true)
For(;;) a While(true) ^
Posted On Saturday 26 February 2011 by Freddie Nash (FredFace)
Incase someone is wondering, for(;;) and while(true) compile identically in CPP and C#. C# is my forte, so I'll demonstrate the intermediate code produced (the same) for each. Consider the following C# Code:
for (;;)
{
if (threadBreaker)
break;
}
while (true)
{
if (threadBreaker)
break;
}
Clearly, it represents two loops which will be broken out of when a variable (bool threadBreaker) is set to true (this is just give something to look at).
After moving each loop to a separate function and compiling (without optimizatins) the IL for the functions is identical, and thus:
.maxstack 2
.locals init ([0] bool CS$4$0000)
IL_0000: nop
IL_0001: br.s IL_0013
IL_0003: nop
IL_0004: ldsfld bool ConsoleTestGround.Program::threadBreaker
IL_0009: ldc.i4.0
IL_000a: ceq
IL_000c: stloc.0
IL_000d: ldloc.0
IL_000e: brtrue.s IL_0012
IL_0010: br.s IL_0017
IL_0012: nop
IL_0013: ldc.i4.1
IL_0014: stloc.0
IL_0015: br.s IL_0003
IL_0017: ret
A quick skim will show up how very inefficiant this is - the need for a stored local variable alone is uncalled for, but it does show that the said variable is assigned the value true (IL_0013 onwards), but it is never compared to anything.
With oprtimizations, the code size is reduced dramatically, but oddly the maxstack is quadrupled in size. Both functions are again, identical:
.maxstack 8
IL_0000: ldsfld bool ConsoleTestGround.Program::threadBreaker
IL_0005: brfalse.s IL_0000
IL_0007: ret
Well, nothing more to say...
Enjoy