Scope of variables in “for” loop

前端 未结 2 930
清酒与你
清酒与你 2021-01-19 18:53

What I have known so far is, multiple declarations inside a block produce an error message and also uninitialized local variable gives garbage value on printing.

But

2条回答
  •  忘掉有多难
    2021-01-19 19:25

    A block is anything in curly braces. A block doesn't have to follow a for do, while, if, etc. Literally any set of statements can be enclosed in their own block scope using curly braces.

    The i in the for loop is not in the loop body scope since it is outside the curly braces. The i in the block is indeed uninitialized and contains garbage. Garbage usually just means "whatever was there before". As often as not, that value will be zero. That doesn't make it any less garbage.

提交回复
热议问题