Should variable declarations always be placed outside of a loop?

前端 未结 6 1406
伪装坚强ぢ
伪装坚强ぢ 2020-12-20 15:39

Is it better to declare a variable used in a loop outside of the loop rather then inside? Sometimes I see examples where a variable is declared inside the loop. Does this ef

6条回答
  •  暖寄归人
    2020-12-20 16:01

    It really doesn't matter, and if I was reviewing the code for that particular example, I wouldn't care either way.

    However, be aware that the two can mean very different things if you end up capturing the 'read' variable in a closure.

    See this excellent post from Eric Lippert where this issue comes up regarding foreach loops - http://blogs.msdn.com/b/ericlippert/archive/2009/11/12/closing-over-the-loop-variable-considered-harmful.aspx

提交回复
热议问题