Home   Cover Cover Cover Cover
 

Declaration rules

class C {
  static int a = 0, b = 1;

  static void Main() {
    int c;
    if (a == 0) {
      int a;   // error 1
      int b;
      int d;
      ...
    } else {
      int d;
      ...
    }
    for (int c = 0; c < 3; c++) {...}  // error 2
    for (int d = 0; d < 3; d++) {...}
  }
}

Error 1: In principle it is allowed to declare a local variable a which has the same name as a field of the corresponding class. However, if the field has already been used before the declaration of the local variable (as it is the case in the example above), the name a is already bound to the field and cannot be redeclared in this method.

Error 2: The variable c was already declared in the outermost block of the Main method. Therefore it is illegal to redeclare it in a nested for loop.

The three declarations of d in the then branch, the else branch and the for loop do not cause any conflics, because they were declared in disjoint declaration spaces.