Finishing an Introductory Look at CIL - Local Variables
(Page 2 of 7 )
Before moving on to local variables, remember that we should state the maximum number of spaces on the stack that we'll require. We'll require two spaces for our program:
.maxstack 2
While the program will function if the number is set to more than is necessary, setting it to less than is necessary causes the program to crash. Alternatively, if we don't specify a value at all, the assembler will choose a default value.
Recall that we also need to manually call for a return at the end of the method, unlike in C#:
ret
Otherwise, the program will crash.
Moving on to local variables, from looking at the source of the C# version of the prime number program, we can see that four local variables are defined: i (the number being tested for primality), prime (a boolean value indicating whether or not the number is prime), limit (the square root of the number, up to which we check for factors – think of factors in pairs, one of the pair being less than the square root and one being greater than the square root, or the square root itself being a factor) and f (a possible factor, between two and the square root of the number).
In CIL, local variables aren't defined as they are in C#. Instead of defining them as we need them at various parts of the method, we need to define them all at once near the top of the method. Let's do that now:
.locals init (int32 i, int32 limit, int32 f)
This method of defining variables is indeed different, but it shouldn't seem too scary. We simply give each variable a name and a type. Also, notice how we have not included our prime variable. In C#, we need it in order to mark a number as not prime when breaking out of the loop (otherwise, how could we distinguish between an early break and a complete run through the loop?). However, such a device is unnecessary with CIL, and soon we'll see why.
So far, the CIL program should look like this:
.assembly extern mscorlib {}
.assembly FindPrimes {}
.class public FindPrimes
{
.method public static void Main(string[] args)
{
.entrypoint
.maxstack 2
.locals init (int32 i, int32 limit, int32 f)
ret
}
}
Next: Loops >>
More ASP.NET Articles
More By Peyton McCullough