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

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

    I think you're all confusing C++ and C#.

    In C++, it used to be that the scope of a variable declared in a for expression was external to the block that followed it. This was changed, some time ago, so that the scope of a variable declared in a for expression was internal to the block that followed it. C# follows this later approach. But neither has anything to do with this.

    What's going on here is that C# doesn't allow one scope to hide a variable with the same name in an outer scope.

    So, in C++, this used to be illegal. Now it's legal.

    for (int i; ; )
    {
    }
    for (int i; ; )
    {
    }
    

    And the same thing is legal in C#. There are three scopes, the outer in which 'i' is not defined, and two child scopes each of which declares its own 'i'.

    But what you are doing is this:

    int i;
    for (int i; ; )
    {
    }
    

    Here, there are two scopes. An outer which declares an 'i', and an inner which also declares an 'i'. This is legal in C++ - the outer 'i' is hidden - but it's illegal in C#, regardless of whether the inner scope is a for loop, a while loop, or whatever.

    Try this:

    int i;
    while (true)
    {
        int i;
    }
    

    It's the same problem. C# does not allow variables with the same name in nested scopes.

提交回复
热议问题