Monday, February 19, 2007 12:55 PM bart

Answers to C# Quiz - "Something weird"

I told you guys it was trivial :-). First of all, there's nothing wrong with the code:

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 }

Why? C# doesn't care about spacing; it could have written this as well:

1 class Weird { static void Main() { int i = 1; for (i = 0; i < 100; i++) { System.Console.Write('.'); } while (i <= 100); } }

Or - the more familiar form:

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 } 10 while (i <= 100); 11 } 12 }

The funny thing about it is the way it was created, but turning a do...while-loop into a for-loop without paying attention of the while portion. Actually, it had a totally different form which was a bit too heavy to put in here as a simple quiz. Originally, the loop termination condition was some boolean ok value that represents a test result of one single execution, do-whiling till the test fails at some random input - it was turned into a do-it-100-times kind of loop, so I ended up with some mixing of the following form:

bool ok; for (int i = 0; i < 100; i++) { //create some random input "someinput" ok = Foo(someinput); } while (ok);

This reflects the fact that both loop constructs have a totally different set of characteristics when it comes down to the use of loop condition variables and the overall structure. In this context, did you know there's a subtle difference between the two (wrong!) fragments below:

class Loops { static void Main() { for (int i = 0; i < 100; i++); { System.Console.Write("."); }; } }

class Loops { static void Main() { for (int i = 0; i < 100; i++);; { System.Console.Write("."); }; } }

The result? One dot on the screen. At compilation? One warning in fragment one, no warning in fragment two. This might better deserve the nominator "weird".

To conclude, I like Eber's summary of an "optical illusion" because that's exactly what it is. In this case, a kind of philosophical question is: "why is do...while (condition) terminated with a semicolon?" (as soon as the do part disappears, you end up with an infinite loop after all). Another typical optical illusion is this one:

1 int x = 18; 2 if (x > 16) 3 if (x > 18) 4 Console.WriteLine("More than 18"); 5 else 6 Console.WriteLine("Less than or equal to 16");

What will be printed on the screen? No rocket science, but coding style does matter!

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

Filed under:

Comments

# re: Answers to C# Quiz - "Something weird"

Monday, February 19, 2007 2:10 PM by Sadek Drobi

good warning for the one ";"

thats what i like about c# that it is explicit, but i didnt get the semicolon after the bracket of the end of for loop.

still no weired compiler behaviour, it is as u mentioned an optical illusion! :)