In the following piece of C++ code:
for (int i=0; i<10; i++)
{
int y = someFunctionCall();
//Some statements
}
is the variable (y) allocated each time the loop iterate and then de-allocated when the iteration is done, or it's allocated one time for all loop iterations?
Is the mentioned code equivalent to the following?:
int y;
for (int i=0;i<10;i++)
{
y = someFunctionCall();
//Some statements
}
In Python, on the other hand, variables declared in if-statements, for-loop blocks, and while-loop blocks are not local variables, and stay in scope outside of the block.
Often the variable that controls a for loop is needed only for the purposes of the loop and is not used elsewhere. When this is the case, it is possible to declare the variable inside the initialization portion of the for.
For the most part, loops do not have their own scope, so the variable's scope will be the scope of wherever the for loop lives. With that in mind, if the for loop is within a function, it will have local scope. One exception would be using let x = something in Javascript.
At the end of each loop iteration, the variable goes out of scope and ceases to exist. That doesn't mean assigning a special value (such as null ) to it; it just means that the memory is available to be used by other things.
It will be allocated on the stack once, when the function is called. Performance-wise, there is no difference between the two ways of doing it (but recall that with the last way, y
will still be in scope after the loop). That the variable appears to be created and destroyed between each iteration (so that it "loses" its value between iterations) is a behavior that is created by the compiler; the actual memory location is the same all of the time.
It's not allocated each time, however it's assigned a new value in each iteration. The loop is within a method, which has its own stack frame. The variable y is allocated in that stack frame.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With