We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpSyntax Questions › int i in for() loop
Page Index Toggle Pages: 1
int i in for() loop (Read 510 times)
int i in for() loop
Sep 1st, 2007, 6:17am
 
I have this code:

 int imax=3;
 for (int i=0; i<imax; i++) {
   for (int i=0; i<imax; i++) {    // ERROR HERE
     print(".");
   }
 }

Semantic Error: Duplicate declaration of local variable "i".
The other occurrence is at location ...

I can fix it by replacing the inner-loop i by j.

But should not the inner-loop i just hide the outer-loop i without causing an error?

alphachapmtl
Re: int i in for() loop
Reply #1 - Sep 1st, 2007, 6:55am
 
Nope, shadowing doesn't work like that in Java (at least at the block level, for instance within a for loop), and the i from the outer level is considered local for the whole outer for block, blocking any redeclaration until the function call is up.  Shadowing is allowed inside functions, where a locally declared variable in a function shadows a class member.  This is generally considered a bad thing, since it can totally mess with your head when you think you're accessing the class variable but it's actually been shadowed a hundred lines earlier in the file you're working on.  See http://www.leepoint.net/notes-java/data/variables/60shadow-variables.html for some examples.

In any case, my advice is to steer clear of this type of thing except for the most trivial of cases - even in a language that would allow nested i loops (are there any common ones?  I know Python has some bizarre scoping, but I don't think it is that weird), it's just not a good idea.  If you needed to reference the outer i, you wouldn't be able to at all (at least with class variable shadowing you can always tack on this to access the class variable instead of the local one), which is not ideal.
Re: int i in for() loop
Reply #2 - Sep 1st, 2007, 9:24am
 
Thanks for the explanation,
I'm learning something about variable scope in blocks.

You're right about unnecessary variable shadowing messing the logic of the code.
In the example I gave, using i and j would be the natural thing to do.
In my original code, the outer loop was far up and out of my mind, so coding the inner loop with i seems natural.
Page Index Toggle Pages: 1