Programming Puzzler
/Quick test for all you programming experts. Will this stupid code compile?
public int InfiniteLoop()
{
while (true)
{
Console.WriteLine("Loopy");
System.Threading.Thread.Sleep(1000);
}
}
Note: All the namespaces are in place and the WriteLine and the Sleep are perfectly legal calls.
Turns out that it compiles just fine. The compiler is smart enough to work out that the method will never complete because it contains an infinite loop. This means that although the signature of InfiniteLoop defines it as returning an integer the compiler just says "Since the method never ends I'm not going to worry about it not returning a value when it says it should".
I'm not sure I agree with this behaviour. I saw it in the lab this morning and it surprised me. I would expect at least a warning, in case I'd put a loop in when I didn't mean to.
The compiler doesn't fail to compile programs containing unreachable code either, although this does produce a warning.