Here is the code (I haven’t yet completed this quixort):

private static void QuickSort(int[] array, int start, int end) { if (start == end) return; int pivot = start; int left = start, right = start + 1; for (int i = start + 1; i <= end; ++i) { if (array[i] <= pivot) { int temp = array[right]; array[right] = array[i]; array[i] = temp; ++left; ++right; } } int temp; QuickSort(array, start, left); QuickSort(array, right, end); } 

The compiler asserts that the temp variable cannot be declared after the cycle of fors, because it is already declared there. But after all, in the cycle of forms, the scope is completely different? And after this cycle, the variable temp, if it was there, disappears. So why I can not declare the second variable temp, but already seemingly in a different scope?

  • one
    You are right with the visibility zone, but here the compiler itself with the debbager is just so structured that it is impossible to make two local variables with the same name in one procedure, apparently, because there is only one array of local variables for the entire function. - nick_n_a
  • "... because this name is used in the enclosing local scope to define a local variable or parameter" - Alias
  • You will have to give a different variable name. I don’t see a violation from CS0136 ... Yes, I have the same behavior. - nick_n_a
  • one
    I do not see either. There is another example. - Mark Pavlovich

2 answers 2

The scope of a local variable in C # is the entire block, not just the part from the declaration to the end of the block.

The scope of the local variable is declared.

In this case, the variable cannot be accessed until the text position in which it is declared:

This is a variable in the textual position that precedes the local_variable_declarator of the local variable. It is a variable-time variable to declare your local variable.

Despite the fact that in your example there is no point where you can refer to two temp variables at the same time, their visibility areas overlap, and you get a compilation error.

    The scope of the temp variable is those curly braces in which it is declared. Even in the lines before its announcement, it is considered visible, although it cannot be used.

    This is easy to see with an example (note the difference in the error texts):

     // error CS0841: Cannot use local variable 'foo' before it is declared Console.WriteLine(foo); // error CS0103: The name 'bar' does not exist in the current context Console.WriteLine(bar); string foo;