0

I have a game update loop that's executed about 30 times a second. I was wondering what happens to variable memory once it leaves the method scope, example.

void updateLoop(double delta)
{
    double TestVar = 1; // << Does this variable get "deleted from memory"
                        // once it this method completes? What exactly happens?
}
simonc
  • 41,632
  • 12
  • 85
  • 103
Oliver Dixon
  • 7,012
  • 5
  • 61
  • 95
  • everything declared in the method that's not a pointer to something will get removed once it exits. – SSpoke Aug 14 '13 at 06:56
  • 1
    [This Wikipedia article](http://en.wikipedia.org/wiki/Call_stack) might help you understand where and how function local variables (and function arguments) are stored. – Some programmer dude Aug 14 '13 at 06:57

2 Answers2

1

Here TestVar is a local variable.

It means that it is limited in scope to all the code below the declaration until the end of the enclosing block. That is from its declaration to the end of the block (until the }).

Its lifetime is As long as execution is inside the block.

From the standard :

3.7.3 Automatic storage duration [basic.stc.auto]

Block-scope variables explicitly declared register or not explicitly declared static or extern have automatic storage duration. The storage for these entities lasts until the block in which they are created exits.

It means : Automatic/Local non-static variables Lifetime is limited to their Scope.

Community
  • 1
  • 1
Pierre Fourgeaud
  • 14,290
  • 1
  • 38
  • 62
  • So if I was to create new objects in there how does the computer deal with them in memory after the block? – Oliver Dixon Aug 14 '13 at 07:15
  • @OllyDixon It depends on how you create your new objects. If you declared them in the same way as `TestVar`, they will be destructed at the end of the scope. That is not the same for `static` variables or if you allocate the memory dynamically. – Pierre Fourgeaud Aug 14 '13 at 07:26
1

Yes, it get destroy every time the function execution ends (in your case its get created/destroyed for 30 times per second).

if you want it to keep value after execution, use member variable of the class where this function belong to instead or use static variable or global variable.

void updateLoop(double delta)
{
    static double TestVar = 1; 
}

But in case you are trying to allocate memory dynamically inside this function, make sure you always perform delete operation on pointer you allocated memory to or you will get memory leaks. Because the pointer you allocated will be destroyed once program is out of scope, but memory allocated where this pointer pointed to will not destroyed. So you will loss the reference to it and hence memory leaks.

void updateLoop(double delta)
{
    int* TestVar = new int;
    // your codes
    delete TestVar; 
}
someone_ smiley
  • 1,006
  • 3
  • 23
  • 42