Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Local variables defined inside for loops in C++

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
    }
like image 324
Ahmed Adel Avatar asked Sep 16 '12 11:09

Ahmed Adel


People also ask

Are variables in for loops local variables?

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.

Can a variable be declared inside for loop in C?

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.

Are variables in a for loop local or global?

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.

Are local variables made inside a loop destroyed?

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.


2 Answers

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.

like image 123
Aasmund Eldhuset Avatar answered Sep 21 '22 01:09

Aasmund Eldhuset


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.

like image 44
Man of One Way Avatar answered Sep 21 '22 01:09

Man of One Way