http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47686

           Summary: scope of variables declared within a nested for loop
                    is trivial
           Product: gcc
           Version: 4.1.2
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c++
        AssignedTo: unassig...@gcc.gnu.org
        ReportedBy: chal...@sonalysts.com


I am using gcc v. 4.1.2 on red hat enterprise linux x86_64 (64 bit) kernel:
2.6.18-238.1.1el5.  Declaring a variable within a nested for loop causes the
variable to become static when uninitialized.  for example:

for(int i =0; i < 5; i++) {
   int x;
   for(int j = 0; j < 5; j++ {
      x += i * j;
   }
}
The first iteration of the outer loop would result in x having a value of 15.
The second iteration of the loop would cause the "newly" declared x to hold on
to its value of 15 and continue to add on to that value based on the inner
loop.  Now I know good coding conduct would be to declare that accumulator
variable outside of the looping structure or to at least initialize the x to 0
or some arbitrary number each iteration.  From what I saw, using my debugger
(gdb) it shows that the "newly" declared variable is using the same memory
block every single iteration but never clearing the value within that memory
block.  The first uninitialized declaration of the x integer will produce a
debugger output of some arbitrary value assigned by the debugger.  It does not
seem right to have the x integer in the outer loop act like a static variable.

Any input on this would be greatly appreciated!

Reply via email to