I accidentally combined a while
loop with a do while
loop to create this confusing construction:
do while (false)
{
Console.WriteLine(1);
}
while (true);
This doesn't throw any errors, but it also doesn't write anything to the console. In fact, it doesn't seem to do much of anything.
Compare that to this regular do while
, which prints 1
to the console indefinitely:
do
{
Console.WriteLine(1);
}
while (true);
Why doesn't that first construction throw an error? What is it doing?
I'm going to reorganize your sample a little bit. Hopefully that'll make what's happening a little clearer.
do
while (false)
{
Console.WriteLine(1);
}
while (true);
Do you see it now? It comes down to this: absent a code block ({}
), the first statement after a do
statement will be interpreted as the loop body.
In your sample, that first statement is the while (false)
loop you accidentally declared. Since that inner loop is now the body of the outer loop, it's being repeated while (true)
- that is, forever.
Of course, since false
is never true
, the line Console.WriteLine(1);
is never getting executed. So your program will loop forever, but it will never print anything to the console.