What is the scope of the counter variable in a for loop?

前端 未结 4 844
灰色年华
灰色年华 2021-02-14 07:31

I get the following error in Visual Studio 2008:

Error 1 A local variable named \'i\' cannot be declared in this scope because it would give a different meaning

4条回答
  •  孤城傲影
    2021-02-14 07:52

    The incrementor does not exist after the for loop.

    for (int i = 0; i < 10; i++) { }
    int b = i; // this complains i doesn't exist
    int i = 0; // this complains i would change a child scope version because the for's {} is a child scope of current scope
    

    The reason you can't redeclare i after the for loop is because in the IL it would actually declare it before the for loop, because declarations occur at the top of the scope.

提交回复
热议问题