Memory allocation of local variables within nested {}

760 views Asked by At

I have few queries on allocation of var2 local variable, in reference to the below code.

  1. When will the memory of a local variable var2 allocated? Whether var2 will be allocated whenever function is called or whenever condition is satisfied and control goes inside if(Threshold > 5)?

  2. Does keeping var2 within condition just only restrict the scope of local variable?

  3. 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;
    }
}
2

There are 2 answers

7
Sourav Ghosh On

1. When will the memory of a local variable 'var2' allocated.

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.

2. Is keep 'var2' within condition just only restricts the scope of local variable.

Right you are. var2 scope is limited to the inner block only.

3. Whether keeping 'var2' within condition will improve processing speed as variable is not allocated and de-allocated every time function is called.

Not related. Anyway this (variable definition) will be a compile time operation. Only the scope is changed based on the block of definition.

1
Aki Suihkonen On

Depending on optimization level, the variable may never be allocated at all. An optimizing compiler can throw all unused variables away, as well as reuse the memory for two variables having non-overlapping lifetime.

Checking from assembler output (gcc -S file.c) one can often see all the used variables allocated immediately after the function entry:

 sub r1, $108   ;;  stack space needed for array[100] (and some)

corresponding to:

 void func(bool a)
 {
      if (a)
      {
           char array[100];
           subfunc(array, 100);
      } else {
           char array2[15];
           subfunc2(array2, 15);
      }
 }