The C# team posts answers to common questions and describes new language features
Q: Why can't I do the following:
static void Main(string args)
for(int i=0; i<100; i++)
int i = 0;
the compiler gives me an error on the “int i = 0;” part of the code.
A: This is correct behavior, and 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 i is therefore the entire Main() 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.
[Author: Eric Gunnerson]
Why, then, is the following valid...
for (int i=0; i<example.Length; ++i) Console.WriteLine("Firet: "+example [i]);
for (int i=0; i<example.Length; ++i) Console.WriteLine(example [i]);
Please answer ASAP
Yes, the way you use is correct. It's 2 different child scope. Here is an example:
for (int i = 0; i < 100; i++)
// Correct here. Child scope
for (int i = 0; i < 5; i++)
// Correct here. Child Scope
int i = 0;
// Error here. Main Scope
int i = 20;
I have arrived here a couple of years later, I know, but I would just like to point out that this is a pretty stupid rule. Can we use the external "i" before the for loop? Nope. Because it was not declared yet. Can we use the innermost "i" (the one declared in the for()) after the for loop scope ends? No, because the variable scope has ended right there.
What I would concede to is IF, AND ONLY IF, a warning was issued if you declared the outer "i" before that for loop. Then I can see a possible screw up. Even though whoever writes codes like that would be asking for it, the rule should quite simple: the one in the most restrictive scope is the valid one. But a nice warning would be great there.
Otherwise we can simply go back to the C days, where we h
because you are declaring i twice in the same block of code ie main. you are declaring in a loop than again after the loop. if you change the 2nd to i=0 it will compile.