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

我的梦境 提交于 2020-01-03 08:13:11

问题


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?


回答1:


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!)




回答2:


Yes, it's an infinite loop.

Examples:

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

while (true) { }

do { } while (true)




回答3:


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.




回答4:


It's an infinitely loop. Effectively, its the same as this:

while (true)
{
}



回答5:


for (; ;) { } is infinite loop, you are correct.

if you want to use it, then you have to put some condition in your loop body, so that it can exit out from loop.

for (; ;) 
{
    if (conditionTrue)
        break;
    else
        continue;
} 



回答6:


There are no defaults. Nothing is initialised, nothing is incremented and there's no test for completion.




回答7:


There are no defaults for first and third part (they default to nothing and it would work). The default for conditional expression is true which will make for(;;) effectively an infinite loop. (If the default was supposed to be false, it would have been useless to have such a construct).




回答8:


Just like in C and C++ you can omit any of the three, or all three.




回答9:


Microsoft's C# Programmer's Reference says:

All of the expressions of the for statement are optional; for example, the following statement is used to write an infinite loop:

for (;;) {
   ...
}



回答10:


It's an infinite loop :).



来源:https://stackoverflow.com/questions/697307/what-does-a-c-sharp-for-loop-do-when-all-the-expressions-are-missing-eg-for

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!