Home > database >  What happen to counter variable when a for loop ends in C
What happen to counter variable when a for loop ends in C

Time:12-14

I have to implement an algorithm that can handle the main memory while executing and I was wondering what does happen to a variable that is declared like this (I refer to int i):

for(int i=0; i<100; i  ){
    .....
}

at the end of the for statement is it kept in memory or is "freed" in some way?

CodePudding user response:

For a variable declared inside a for statement, its lifetime ends when execution of the for statement ends. Lifetime is the portion of program execution during which memory is reserved for the object in the C model of computing.

When implementing that model, a compiler theoretically can allocate space for the i you show on the stack (by adjusting the top-of-stack pointer) when the for statement starts and can release that space by a reverse adjustment when the statement ends. In practice, most ordinary compilers plan execution of a whole function and set up one stack frame when the function is started and tear down that stack frame frame when the function ends (with some exceptions, such as for variable length arrays). Within the function, the memory of that stack frame is shared for various purposes according to the compiler’s design.

This means that, when execution of the for loop ends, there is probably no immediate adjustment to the stack pointer. However, the memory for the i variable might or not be reused for other purposes immediately, depending on what other computations the function is doing and how the compiler arranged things.

This is presuming memory was used for i at all. While variables use memory in the computing model the C standard uses, compilers are allowed to generate any code that gets the same observable behavior. (For simple programs, observable behavior is mostly the input and output of a program.) The compiler might use a processor register for i and never keep its value in memory. Immediately after execution of the loop ends, the processor can reuse that register for other purposes.

CodePudding user response:

It depends on where you define your variable.

If you define it before the loop, and just initialize it inside the loop - it will continue to exist after the loop, preserving the value, modified by the last iteration of the loop. Like:

int i;//define variable here

for (i = 0; i < 10; i  )
{
    //some code inside the loop
}

printf("Value of i is: %i", i);//print variable here

Output will be:

Value of i is: 10

In the other case - you can both define and initialize the variable inside the loop (as you did in your example). In this case the variable is being deleted, right after the program leaves the loop, since it leaves a local scope. You can try to pass it to a function, after the loop - you will receive compile error.

  • Related