Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are variables inside a loop (while or for) disposed after the loop has completed?

Tags:

Are variables that are created inside a while or for loop disposed/deleted from memory after the loop is done executing? also, is it a bad coding habit to create temporary variables inside a loop?

in this example, does it create 100 X variables and then dispose of them, or are they disposed on each iteration? thanks. example:

int cc =0; while(cc < 100){     int X = 99; // <-- this variable     cc++;     } 
like image 953
Daniel Valland Avatar asked Oct 24 '14 21:10

Daniel Valland


2 Answers

Scope and lifetime are two different things. For variables defined at block scope without static, they're more or less tightly linked, but they're still distinct concepts -- and you can shoot yourself in the foot if you don't keep them straight.

Quoting the snippet from the question:

int cc =0; while(cc < 100){     int X = 99; // <-- this variable     cc++;     } 

The scope of X is the region of program text in which its name is visible. It extends from the point at which it's defined to the end of the enclosing block, which is delimited by the { and } characters. (The fact that the block happens to be part of a while statement is not directly relevant; it's the block itself that defines the scope.)

Inside the block, the name X refers to that int variable. Outside the block, the name X is not visible.

The lifetime of X is the time during program execution when X logically exists. It begins when execution reaches the opening { (before the definition), and ends when execution reaches the closing }. If the block is executed 100 times, then X is created and "destroyed" 100 times, and has 100 disjoint lifetimes.

Although the name X is visible only within its scope, the object called X may be accessed (directly or indirectly) any time within its lifetime. For example, if we pass &X to a function, then that function may read and update the object, even though the function is completely outside its scope.

You can take the address of X, and save that address for use after its lifetime has ended -- but doing so causes undefined behavior. A pointer to an object whose lifetime has ended is indeterminate, and any attempt to dereference it -- or even to refer to the pointer's value -- has undefined behavior.

Nothing in particular actually has to happen when an object reaches the end of its lifetime. The language just requires the object to exist during its lifetime; outside that, all bets are off. The stack space allocated to hold the object might be deallocated (which typically just means moving the stack pointer), or, as an optimization, the stack space might remain allocated and re-used for the next iteration of the loop.

Also, is it a bad coding habit to create temporary variables inside a loop?

Not at all. As long as you don't save the object's address past the end of its lifetime, there's nothing wrong with it. The allocation and deallocation will very often be done on entry to and exit from the function rather than the block, as a performance optimization. Restricting variables to a reasonably tight scope is a very good coding habit. It makes the code easier to understand by restricting unnecessary interactions between different parts of the code. If X is defined inside the body of the loop, nothing outside the loop can affect it (if you haven't done something too tricky), which makes it easier to reason about the code.

UPDATE: If X were of a type with a non-trivial constructor and/or destructor, creating and destruction of X actually has to be performed on entry to and exit from the block (unless the compiler is able to optimize that code away). For an object of type int, that isn't an issue.

like image 73
Keith Thompson Avatar answered Oct 12 '22 21:10

Keith Thompson


Yes, the variable is created and destroyed N times, unless the compiler optimizes it somehow (which it can, I believe). It's not a very big deal when you have just one int though. It becomes more problematic when you have some complex object recreated 99 times inside your loop.

A small practical example:

#include <iostream> using namespace std;  class TestClass { public:     TestClass();     ~TestClass(); }; TestClass::TestClass() {     cout<<"Created."<<endl; }  TestClass::~TestClass() {     cout<<"Destroyed"<<endl; }  int main() {     for (int i = 0; i < 5; ++i)     {         TestClass c;     }     return 0; } 

In this code TestClass c will be recreated 5 times. IdeOne Demo.

like image 40
FreeNickname Avatar answered Oct 12 '22 19:10

FreeNickname