April 6th, 2006

Cutest Kitten

What goes on in Andy's head - warning, extreme geekiness.

A few days ago I was waiting for something or other to get sorted before I could proceed with the current round of bugfixing (the latest project is very nearly done) when I got into a discussion with channelpenguin about the syntax of the for statement in C#. She was complaining that it felt wrong - it didn't really fit with any other statement in C#, what with having semicolons inside brackets. In fact, the for statement was the one I kept having to check the syntax of when I first started using C#, so I could sympathise with her.

The syntax is:
for (initialisers; expression;iterators)
{
    Stuff();
}


for instance:

for(int myInt = 0;myInt < 5;myInt++)
{
	Console.WriteLine(myInt);
}

meaning "Create an integer. Set it to zero. While said integer is less than 5, output it to the console and then increment it by one."

Now, I thought about how you could write the for statement differently, and I couldn't think of one that was any clearer without expanding it out entirely into its equivalent while statement. Which looks like this:

int myInt = 0;
while (myInt < 5)
{
	Console.WriteLine(myInt);
	myInt++;
}

In fact, the more I thought about it, the more it seemed likely that the for statement was just a macro - and at compile time the for statement was translated into the equivalent while statement, and _that_ was compiled - so that the original syntax statement above would become:

{	
	initialisers;
	While (expression)
	{
		Stuff();	
		iterators;
	}
}

(the braces around the entire of the expanded statement are to make sure that any variables created in the initialisers are local to that code segment)

Fortunately, Visual Studio comes with a neat little disassembler (ILDASM), so I compiled the two above bits of code and they both came out exactly the same, as:

 .locals init ([0] int32 myInt)
  IL_0000:  ldc.i4.0
  IL_0001:  stloc.0
  IL_0002:  br.s       IL_000e
  IL_0004:  ldloc.0
  IL_0005:  call       void [mscorlib]System.Console::WriteLine(int32)
  IL_000a:  ldloc.0
  IL_000b:  ldc.i4.1
  IL_000c:  add
  IL_000d:  stloc.0
  IL_000e:  ldloc.0
  IL_000f:  ldc.i4.5
  IL_0010:  blt.s      IL_0004
  IL_0012:  ret

which gave me a warm glow inside. It's nice to be right about something, especially when you're just stabbing in the dark.

Of course, I'm now curious about .NET's Intermediate Language (which is what that stuff at the end is). So possibly a look into _that_ is in order next.

I

read this all the way to the end
0(0.0%)
understood it
0(0.0%)
thought it was interesting
0(0.0%)
like clicking boxes
16(37.2%)