Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Scope of loop variable.... Error when compiling....

 
Anoop Nair
Ranch Hand
Posts: 70
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
void function1(int x)
{
for(int x=0;x<6;x++);
}

The variable x in red color gives error: Variable with this name already exists.

The x inside the for loop has scope only within the loop. Then why does it give error when compiling???

 
Garrett Rowe
Ranch Hand
Posts: 1296
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because the x that is passed as a parameter to the method is in scope for the entire method. You can't redeclare a variable with the same name as one that is already in scope.
 
Anoop Nair
Ranch Hand
Posts: 70
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
But the for loop is a separate block...

So if i declare a variable with the same name as of the enclosing block, then the variable local to the current block would take precedence...

Thats how it is supposed to work, right??

 
Uli Hofstoetter
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Check out the JLS, section 14.4.2, where your point is covered.
 
Anoop Nair
Ranch Hand
Posts: 70
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot Uli....



 
Adi Kulkarni
Ranch Hand
Posts: 86
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You have declared a local variable in a method already( Say int x ). So it has a scope for that entire method.

In the for loop you are trying to redeclare the same variable again which is not allowed in this case since the variable has already been declared. You can always use that variable in the for loop eg for(x=0 ; x<smthing ; x++) .

In your case you have

method new {
int x = 0; ..................already declared
for ( int x = 0 ; x<smthing ; x++)
{}
}

So you are trying to redeclare a variable which is already in scope. No precedence is applicable in this type of declaration.

When you are having an instance variable with name "x" and a local variable with name "x" , precendence comes into play then when you are trying to access the variables with the name "x" .
In your case both are local variables and secondly you are redeclaring which is not allowed.

~Aditya
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic