Variable declaration curiosity

Just out of curiosity. For example the code below having the same variable "i" use in a different loop
1
2
3
4
5
6
7
8
9
for(int i = 0; ...)
{
  // do something
}

for(int i = 0; ...)
{
 // do something again
}


I know from experience that it will work just fine but what about the memory allocated? Will it be the same or will allocate a new one? Is it right to use the same variable again or just declare a different variable for a different for loop.

Thanks in advance

In C++, i is limited in scope. It is destroyed at the end of the for loop.

It's roughly equivalent to this:
1
2
3
4
5
6
7
{
  int i;
  for (i = 0; ...)
  {
    //do something
  }
} // i is destroyed here as it reaches the end of its scope 
Last edited on
You can safely use the same symbol in different loops.
The declaration of int i exists within the loop and the compiler must enforce that it cannot be accessed anywhere but within the loop.

Whether or not int i shares the same memory however, shouldn't be your concern. It might, or it might not. The compiler may optimize your code. Or it might not. You should treat them as if they're different integers.
In your first loop int i declared and assign as 0.
so here in first loop your int i is local and same in second loop.
but

1
2
3
4
5
6
7
for(int i = 0; ...)
{
     for(int i = 0; ...)
    {
          // do something again
    }
}


above code fails in compilation

1
2
3
4
5
6
7
8
9
int i = 0;
for(;i < condition ...)
{
     
}
for(i = 0; ...)
    {
          // do something again
    }

above code do the same as you shown in your code

1
2
3
4
5
6
7
8
9
int i = 0;
for(;i < condition ...)
{
     // do something
}
for(;i < condition ...)
    {
          // do something again
    }


in above code
here in second loop i will continue from the value of i from first loop.

now in your case when you declared i in your both loop as local when it's work is finished it will free the memory.
Thanks everyone for your comments :). Now I know
Topic archived. No new replies allowed.