Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does a C# for loop do when all the expressions are missing. eg for(;;) {}

I can only assume it's an infinite loop.

Can I leave out any of the three expressions in a for loop? Is there a default for each when omitted?

like image 701
PaulB Avatar asked Mar 30 '09 13:03

PaulB


3 Answers

Yes, it's an infinite loop.

Examples:

for (; ;) { } (aka: The Crab)

while (true) { }

do { } while (true)

like image 95
Alex Fort Avatar answered Sep 17 '22 13:09

Alex Fort


It is indeed an infinite loop.

Under the hood the compiler/jitter will optimize this to (effectively) a simple JMP operation.

It's also effectively the same as:

while (true)
{
}

(except that this is also optimized away, since the (true) part of a while expression usually requires some sort of comparison, however in this case, there's nothing to compare. Just keep on looping!)

like image 29
CraigTP Avatar answered Sep 21 '22 13:09

CraigTP


Yes, that's an infinite loop. You can leave out any of the three expressions, though in my experience it's typically either the first or all 3.

like image 20
Harper Shelby Avatar answered Sep 18 '22 13:09

Harper Shelby