Suppose I declare a loop like this
So is the variable 'i local to the loop, that is each time the control enters the loop a new space is allocated for the variable and the space is deallocated after the completion of loop? Is it true for C99 also?
for(int k = 0;k < 5;k++)
// some work
All the memory (for a function call) is allocated at once regardless of if the loop is executed or not.
No the loop does not allocate and deallocate things every itteration. Why? Effiecancy and its would be prety hard to right a compiler to keep track if the variables are allocated or not, because you have goto statements and could do all sorts of things (That may or may not be considered as bad programming practice).
Just a note: the memory is allocated on the stack enough for all the "auto" variables. However that does not mean the class (If any exist) constructors are called. in most cases I think they are called though.
It is true that k goes into scope at the start of the loop, and goes out of scope when the loop finished.
However, because k is on the Stack, there is absolutely no memory management involved. The Stack is allocated when your program starts, as a big memory space for all local function variables. Stack variables can have constructors and destructor, but besides that no additional memory is allocated. Integers don't have constructors, or destructor, so declaring a local integer is a no-op.
And yes, you can do this in C++ and C99.
See post #13 of that thread for the relevant information from the C++ standard. If you decide to read the other posts make sure you read the whole thread, as some of the earlier statements were incorrect.