What is the difference between infinite while loops and for loops?

前端 未结 6 1777
忘掉有多难
忘掉有多难 2020-12-18 04:24

I see the different conventions used in many books I had read, where you would create infinite loops with either loop structure such as:

while()
   foo();
fo         


        
6条回答
  •  温柔的废话
    2020-12-18 04:52

    They're semantically the equivalent. (x;y;z) { foo; } is equivalent to x; while (y) { foo; z; }. They're not exactly equivalent in further versions of the standard, in the example of for (int x = 0; y; z), the scope of x is the for block and is out of scope after the loop ends, whereas with int x; while (y) x it's still in scope after the loop ends.

    Another difference is that for interprets missing y as TRUE, whereas while must be supplied with an expression. for (;;) { foo; } is fine, but while() { foo; } isn not.

提交回复
热议问题