Saturday, February 17, 2007 7:36 AM bart

C# Quiz - "Something weird"

Time for a new C# quiz - well, sort of. What does the following print on the screen and why (should be trivial)?

1 class Weird 2 { 3 static void Main() 4 { 5 int i = 1; 6 for (i = 0; i < 100; i++) 7 { 8 System.Console.Write('.'); 9 } while (i <= 100); 10 } 11 }

Have fun!

Why this quiz? While preparing another blog post I did quite some copy-paste and replace work, ending up with a similar construction as the one above (although it was less "visible" because of lots of code being commented out). (Tip: To set your mind, I started from a do...while loop and turned it into a for-loop, but I forgot to remove the while-part of the old loop construction, resulting in a somewhat special result.)

Del.icio.us | Digg It | Technorati | Blinklist | Furl | reddit | DotNetKicks

Filed under:

Comments

# re: C# Quiz - "Something weird"

Saturday, February 17, 2007 7:58 AM by Jack

The C# compiler must be a heap of junk to compile the statement.

# re: C# Quiz - "Something weird"

Saturday, February 17, 2007 8:14 AM by Patrik Löwendahl

Hehe, nasty little thing you caught there. At least your console application won't go away before you can read the result of the screen :P

# re: C# Quiz - "Something weird"

Saturday, February 17, 2007 8:43 AM by bart

Hi Jack,

*The* statement? Which one? The noise in the sample has all to do with spacing and C# happens to be one of these languages that doesn't care about spacing (like other C-derivates).

A first sight, when you see it, you might think of a compiler bug but everything that's going on in here is perfectly normal.

-Bart

# re: C# Quiz - "Something weird"

Saturday, February 17, 2007 9:17 AM by Eber Irigoyen

looks like an optical illusion

this is one loop

for (i = 0; i < 100; i++)

7       {

8          System.Console.Write('.');

9       }

this is another

while (i <= 100);

should output 100 dots...

# re: C# Quiz - "Something weird"

Saturday, February 17, 2007 2:20 PM by Sadek Drobi

i dont see what so wired about it, and why jack is so angry about the compiler!

# re: C# Quiz - "Something weird"

Saturday, February 17, 2007 3:30 PM by Michael Lapinsky

This is a good argument as to why, unless it's needed outside of the for-loop, you make your loop variable(s) local to the for-loop by default when using one.

# re: C# Quiz - "Something weird"

Sunday, February 18, 2007 12:34 AM by Tom

you should get 100 dots and an infinite Loop...

Not...? :)

# re: C# Quiz - "Something weird"

Sunday, February 18, 2007 4:00 AM by Christophe Lambrechts

Eum, if I run the program its hangs after the 100th dot. If you make the while les as 100, 10 for example. You get 100 dots and an ending program. Never seen this kind of constructions, is there more of this stuff?

# re: C# Quiz - "Something weird"

Wednesday, February 21, 2007 2:11 AM by Shail

It shud be 100 dots... that's it as while will satisfy the conditiona and simply exit the program.