Finishing an Introductory Look at CIL - Loops Continued
(Page 4 of 7 )
Now it's time to move on to the second step. If the flow of the program isn't interrupted by branching in the previous step, then the flow of the program will continue to this step, which is, in the program, located immediately after.
The third step in our list is the performance of whatever is in the body of the loop. So, we simply need to print out the value of the counter. This part isn't hard, and we did something like it in the last part:
// loop contents
ldstr "Number: {0}"
ldloc i
box int32
call void [mscorlib]System.Console::WriteLine(string, object)
Now comes the counter. We have to add one to the value of the counter. This involves putting both numbers on the stack:
ldc.i4.1
ldloc i
Adding the two values together is extremely simple:
add
To finish up, we simply store the value back in the counter variable:
stloc i
All that remains in our loop is to go back to the condition section of our method. This is done through an unconditional branch:
br.s loop_condition
Finally, we need to provide a label after the loop, which our condition section jumps to if the condition is false:
loop_done:
ldstr "Done!"
call void [mscorlib]System.Console::WriteLine(string)
Here's the completed program:
.assembly extern mscorlib {}
.assembly LoopTest {}
.class public LoopTest
{
.method public static void Main(string[] args)
{
.entrypoint
.maxstack 2
.locals init (int32 i)
// assign 1 to i
ldc.i4.1
stloc i
loop_condition:
ldloc i
ldc.i4 10
bgt loop_done
// loop contents
ldstr "Number: {0}"
ldloc i
box int32
call void [mscorlib]System.Console::WriteLine(string, object)
// loop counter
ldc.i4.1
ldloc i
add
stloc i
// check the value of i again
br.s loop_condition
loop_done:
ldstr "Done!"
call void [mscorlib]System.Console::WriteLine(string)
ret
}
}
Next: The Outer Loop >>
More ASP.NET Articles
More By Peyton McCullough