Apr. 6th, 2006

andrewducker: (Cutest Kitten)
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 [livejournal.com profile] 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.

[Poll #705445]

August 2025

S M T W T F S
      1 2
3 4 5 6 7 89
10111213141516
17181920212223
24252627282930
31      

Most Popular Tags

Style Credit

Expand Cut Tags

No cut tags
Page generated Aug. 9th, 2025 08:18 am
Powered by Dreamwidth Studios