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

前端 未结 4 853
灰色年华
灰色年华 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:54

    Just some background information: The sequence doesn't come into it. There's just the idea of scopes - the method scope and then the for loop's scope. As such 'once the loop terminates' isn't accurate.

    You're posting therefore reads the same as this:

    int i = 0; // scope error
    string str = ""; // no scope error
    
    for (int i = 0; i < 3; i++)
    {
      string str = "";
    }
    

    I find that thinking about it like this makes the answers 'fit' in my mental model better..

提交回复
热议问题