Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Generally, when you define a variable within a function, the memory allocation is done at runtime and the variable is stored within the stack, which represents the storage system for these kind of variables: local variables.</p> <p>Yes. In the example you provide, the variable a is created 'i' times following this process:</p> <pre><code>While Loop Function f() Push variable a into stack Function f logic Pull variable a from stack End Function f() End While </code></pre> <p>So the general behavior for local variables (Variables within a function or block) is to be allocated upon declaration within their scope (function or block) by being pushed inside the stack and to be "freed" when the scope finalizes (end of function or block) by being pulled from the stack.</p> <p>This is not dynamic allocation but automatic allocation. You can perform dynamic allocation only by using the <em>new</em> operator and your variables will be allocated at runtime within a special area of the memory we call <em>the heap</em>. You have to be careful with dynamic allocation, because you need to explicitely use the <em>delete</em> operator in order to free it.</p> <p><em>Note: The former explanation about the stack was a simplification. The variables are not really pulled from the stack. The stack is controlled with two pointers: one points to the base of the stack, and the other points to the top, the next available position. When a function is called, its variables are added to the stack modifying the position of the second pointer, when the function ends, this pointer takes the same value it had at the beginning of the function effectively freeing the memory used within the function. Therefore the variables are not really pulled, you will just overwrite them in following iterations with the stack.</em></p> <p>For more information you can refer to <em>C++ Primer Plus Chapter 9. Memory Models and Namespaces</em></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload