Today I really fell over while trying to answer a question about a (fairly stupid) C# expression. It went something like the following:
Consider the following code:
int i = 0;
while (i < 10)
{
Console.WriteLine(i++);
}
while (i >= 10);
This code:
- Will not compile
- Will print numbers from 0..9
- Will print numbers from 0..9 and then 9 forever
- Will print numbers from 0 to ∞
Something like this. At first I thought this wouldn’t compile, but in fact my SnippetCompiler ate it just fine. I thought I was going insane. Then I assumed that this construct is, in fact, allowed (maybe a bug in the C# language spec?) and it acts as a double-ended do, cycling the precondition while before cycling the postcondition while, thus yielding the answer 4.
And then it finally hit me: a while loop doesn’t need a comma after it. What this meant is that you could write the code as follows:
int i = 0;
while (i < 10)
{
Console.WriteLine(i++);
}
// empty while loop!
while (i >= 10);
It was a trick question, of course, but it goes to show that vigilance against blatant trickery is often more useful than scientific analysis. Another lesson learned.