Scope of variables in “for” loop

前端 未结 2 885
清酒与你
清酒与你 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.

    0 讨论(0)
  • 2021-01-19 19:33

    The scope of a variable declared in the first part of the for loop is all three parts of the for plus the loop body. In your case the body of the loop is a compound statement, and you declare another variable named i in that block, so it masks the i declared in the for.

    So in your piece of code there are three relevant scopes:

    1. The body of the main function
    2. The three parts of the for loop.
    3. The body of the for loop.

    And each of them is "internal" to the other, so a variable declared at one of these scopes masks a variable of the same name in a higher scope.

    To further illustrate this, if we modify your code as follows:

    int main()
    {
        int i = 9;
        printf("outer i: %d\n", i);
        for(int i = 5;i>0;printf("middle i:%d\n", i),i--){
            int i = 7;
            printf("inner i: %d\n",i);
        }
        printf("outer i: %d\n", i);
    }
    

    The output is:

    outer i: 9
    inner i: 7
    middle i:5
    inner i: 7
    middle i:4
    inner i: 7
    middle i:3
    inner i: 7
    middle i:2
    inner i: 7
    middle i:1
    outer i: 9
    

    As for why your code is printing 0 inside of the loop, an uninitialized variable may have any value, including 0. So just because it's printing 0 doesn't mean it's not garbage.

    0 讨论(0)
提交回复
热议问题