Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Definition of the scope of variables declared in the initialization part of for-loops? [duplicate]

Tags:

scope

c#

Possible Duplicates:
confused with the scope in c#
C# Variable Scoping

I am curious about the design considerations behind the scope of variables which are declared in the initialization part of for-loops (etc). Such variables neither seem to be in-scope or out-of scope or am I missing something? Why is this and when is this desired? Ie:

for (int i = 0; i < 10; i++)
{
}

i = 12;       //CS0103: The name 'i' does not exist in the current context

int i = 13;   //CS0136: A local variable named 'i' cannot be declared in this scope 
              //because it would give a different meaning to 'i', which is already 
              //used in a 'child' scope to denote something else
like image 861
Avada Kedavra Avatar asked Oct 10 '22 08:10

Avada Kedavra


1 Answers

The loop variable is scoped to the loop itself. This is why you see the expected result of i not being available outside the loop.

The fact you can't declare i outside the loop is a bit more puzzling but is to do with the fact that once compiled all the variable declarations can be considered to be at the beginning of the block they are declared in. That is your code in practice is the same as:

int i;

for (int i = 0; i < 10; i++)
{
}

i = 13; 

Hopefully it is obvious here that you have a name collision. As for why it works like that I can't tell you for sure. I'm not that up on what compilers do under the hood but hopefully somebody else will pop up and explain why.

like image 188
Chris Avatar answered Oct 18 '22 02:10

Chris