life span of variable?

If a variable is declared in a block or for loop block, we all know the scope of a variable are usually in that block. But how about life span?

for example the following code

1
2
3
4
5
6
7
8
while(condition) {
    ....
    for(;;) {
        int i;
        ....
    }
    ...
}


if we repeat while loop, every time when we get into the for loop, an i will created and used? but what about the old i? Is is destroyed? I am worrying about the memory will be used up if I do this. Thanks.
closed account (o1vk4iN6)
It's lifespan is the duration of one for loop. So "i" would be constructed and destroyed for every for loop that is run.

http://ideone.com/OY9pF1
Last edited on
if we repeat while loop, every time when we get into the for loop, an i will created and used? but what about the old i? Is is destroyed?


Yes.

For basic types like int this doesn't matter because construction/destruction does not require any work. However for complex types which are expensive to construct/destruct, you want to avoid declaring them in loop bodies for this very reason.

I am worrying about the memory will be used up if I do this.


It will not use any additional memory. The memory the function uses is all allocated "up front" at the start of the function. The "new" 'i' will likely use the same space in memory as the old 'i', despite it having been destructed/reconstructed.


This is kind of an oversimplification of how the stack works... but the point is it won't use more memory... but for complex types it will require more CPU time to recreate and destroy it every loop.
Thanks, if it is a class type, and no destructor are explicitly defined. Will it be destroyed? Thanks.
Why keep it if not needed. Well if the for loop was to run the second time, i no longer exists as it was removed from memory and it get re-initialized.

I believe that is what's happening.
@northfly

Thanks, if it is a class type, and no destructor are explicitly defined. Will it be destroyed? Thanks.



If you did not define explicitly the destructor then the compiler will define it implicitly. Otherwise the compiler will issue a compilation error because it will be unable to generate the object code.
Thanks´╝ü
Topic archived. No new replies allowed.