I have few queries on allocation of var2
local variable, in reference to the below code.
When will the memory of a local variable
var2
allocated? Whethervar2
will be allocated whenever function is called or whenever condition is satisfied and control goes insideif(Threshold > 5)
?Does keeping
var2
within condition just only restrict the scope of local variable?Does keeping
var2
within condition improve processing speed as variable is not allocated and de-allocated every time function is called?
void fun1(int Threshold)
{
int var1 = 0;
if(Threshold > 5)
{
int var2 = 0;
}
}
The memory is mapped (if the variable is allocated, i.e., variable does not get optimized out by the compiler) at compile time. The stack is allocated when the program is loaded into memory. So, to speak strictly, it does not have any impact (cost) on the run-time.
Right you are.
var2
scope is limited to the inner block only.Not related. Anyway this (variable definition) will be a compile time operation. Only the scope is changed based on the block of definition.