Blog Post · 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:
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:
.locals init ( bool CS$4$0000)
IL_0001: br.s IL_0013
IL_0004: ldsfld bool ConsoleTestGround.Program::threadBreaker
IL_000e: brtrue.s IL_0012
IL_0010: br.s IL_0017
IL_0015: br.s IL_0003
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:
IL_0000: ldsfld bool ConsoleTestGround.Program::threadBreaker
IL_0005: brfalse.s IL_0000
Well, nothing more to say...