2

In my mental model, counter variables defined inside for become private because it cannot be access from outside as follows.

    for (int x = 0; x < 2; x++) ;
    //Console.WriteLine(x); x does not exist in the current context

My confusion occurs when I declared the same variable as follows,

    for (int x = 0; x < 2; x++) ;
    //Console.WriteLine(x); x does not exist in the current context, but why cannot I declare
    //int x = 1;

Why does the compiler disallow me to declare a variable with the same name as another inaccessible variable? It does not make sense to me. :-)

To make more confusing compare it with

    {
        int x = 1;
    }
    {
        int x = 2;
    }

which is allowed by the compiler. But both below are not allowed.

static void Foo()
{
    int x = 1;
    { int x = 2; }
}

static void Bar()
{
    { int x = 2; }
    int x = 3;
}
kiss my armpit
  • 3,413
  • 1
  • 27
  • 50
  • 4
    This is explained in [C# Variable Scoping](http://stackoverflow.com/questions/2049330/c-sharp-variable-scoping). – CodeCaster Mar 02 '14 at 12:31

3 Answers3

3

This behaviour is covered in section 3.7 of the language spec. It says, “The scope of a local variable declared in a local-variable-declaration (8.5.1) is the block in the which the declaration occurs”.

The scope of x is therefore the entire function, and that means that the use in the for loop is a re=use, and therefore is not allowed.

This behavior is inteded to make incorrect re-use of variable names (such as in a cut and paste) less likely.

aleroot
  • 71,077
  • 30
  • 176
  • 213
1

aleroot already gave the answer to your first part. I want to answer second part of your question.

{
     int x = 1;
}
{
     int x = 2;
}

which is allowed by the compiler.

Yes, because there is no local variable x in the same scope or any nested scope. For example;

static void Main()
{
    int x;
    {
        int y;
        int x; // Error - x already defined in same scope or parrent scope.
    }
    {
        int y; // OK - there is no y in the same scope or any nested scope.
    }
    Console.Write (y); // Error - there is no y in same scope of any parrent scope.
}
Community
  • 1
  • 1
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
  • If the first `int x;` is moved to the last row, for example after `Console.WriteLine(y);` the compiler is still unhappy. In my mental model, it should not be a problem because it comes last. – kiss my armpit Mar 02 '14 at 12:52
  • 1
    @TheLastError It is because there is an already defined `x` in child scope. You can't declare _local-variable-declaration_ in current or parrent scope if there is an already in child scope (doesn't matter comes last or first). – Soner Gönül Mar 02 '14 at 13:02
  • OK. Thanks. It is counter intuitive at a glance. :-) – kiss my armpit Mar 02 '14 at 13:03
-1

Couse for loop almost declared x varible inside it, so u cant redeclared x varible, as can exists only one declaration in scope.

andrey.rtv
  • 11
  • 3