Scope of variables in “for” loop

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

提交回复
热议问题