Why can't we define a variable inside a while loop?

后端 未结 6 1295
星月不相逢
星月不相逢 2020-12-03 03:27

We can do:

using (Stream s ..)

and:

for (int i ...)

Why can\'t we as well do something like:



        
6条回答
  •  鱼传尺愫
    2020-12-03 03:33

    Don't know for certain but here is my educated guess.

    The for case works because it actually has 3 parts.

    1. The iteration variable
    2. The terminating condition
    3. The increment

    These 3 run differing amounts of times. #1 runs only once, #2 runs number of iterations +1 and #3 runs once per iteration. Since #1 runs only once it's a nice and clean place to define a variable.

    Now lets examine the while loop. It only has 1 part and it runs every iteration + 1. Since it runs every single time it's not a great place to define a variable which must necessarily be a part of the condition. It raises questions like

    • Should the define happen once or once per iteration? If it's the latter how many people will misunderstand this and mess up the conditional? If it's the former then you have a complete statement of which only part executes once per query
    • How do multiple variable defines behave?

    I'm guessing the complexity / ambiguity is one of the reasons why it's not allowed. That and it's probably never been high on the priority list.

提交回复
热议问题