home comics writing pictures archive about

2018-03-25 - In IL: Print the Alphabet (while)

In IL

The while loop is the simplest form of loop. It simply repeats the specified operations as long as the specified condition is true. To show off the while loop we are going to use a program that prints out the letters of the alphabet.

Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CsWhile
{
class Program
{
static void Main(string[] args)
{
char ch = 'A';
while(ch <= 'Z')
{
Console.Write(ch);
ch++;
}
Console.WriteLine();
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

As you can see this is a very simple program. We start at the letter A and then print and increment it until it's the letter Z. This works because characters are actually just numbers and in the encoding used by C# all capital letters are continuous and in order.

Now let's compile this program and see what we get.

Main
.method private hidebysig static void Main(string[] args) cil managed
{
.entrypoint
// Code size 27 (0x1b)
.maxstack 2
.locals init ([0] char ch)
IL_0000: ldc.i4.s 65
IL_0002: stloc.0
IL_0003: br.s IL_0010
IL_0005: ldloc.0
IL_0006: call void [mscorlib]System.Console::Write(char)
IL_000b: ldloc.0
IL_000c: ldc.i4.1
IL_000d: add
IL_000e: conv.u2
IL_000f: stloc.0
IL_0010: ldloc.0
IL_0011: ldc.i4.s 90
IL_0013: ble.s IL_0005
IL_0015: call void [mscorlib]System.Console::WriteLine()
IL_001a: ret
} // end of method Program::Main
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81

As you can see there's no special looping instructions. Instead we just get a couple of branching instructions. We start by initializing our variable to 65 ('A') and then we jump to a point near the end of the function. There we find a second branch that tests if the local variable is less than or equal to 90 ('Z') and jumps backwards in the function if it is. There we find the innards of our loop where we print out and increment the local variable. Then we find ourselves at the second branch point again and perform the test again. If it's true we repeat or loop again and if it's false we continue on and the function ends.

Next time we will look at other kinds of loops.

Comments: