Finishing an Introductory Look at CIL - The Outer Loop
(Page 5 of 7 )
Returning to our main task, we now need to recreate the loops of our program in CIL. Here's the body of our method:
for (int i = 2; i <= 1000000; i++)
{
bool prime = true;
int limit = (int)Math.Sqrt(i);
for (int f = 2; f <= limit; f++)
{
if (i % f == 0)
{
prime = false;
break;
}
}
if (prime)
{
Console.WriteLine(i);
}
}
Console.WriteLine("Done!");
As you can see here, we have two loops, one nested in the other. Let's first tackle the outer loop, which is really quite simple. This is done in exactly the same way as our last example, with one exception. Remember how we eliminated the boolean variable? This is because rather than being forced to continue the rest of the outer loop after breaking from the inner one, we can instead jump directly to the next iteration of the outer loop. This is done by jumping straight to the incrementation stage. So, this stage will not require a label (if this isn't clear now, it will become clear later):
ldc.i4.2
stloc i
outer_condition:
ldloc i
ldc.i4 1000000
bgt outer_done
// CONTENTS OF THE LOOP GO HERE
...
outer_counter:
ldc.i4.1
ldloc i
add
stloc i
br.s outer_condition
outer_done:
ldstr "Done!"
call void [mscorlib]System.Console::WriteLine(string)
If you understood the last example, then this part shouldn't be strange at all. We're doing the exact same thing here, with the exception of an added label.
Next: The Inner Loop >>
More ASP.NET Articles
More By Peyton McCullough