Search code examples
blocklifetime

lifetime of variables defined inside block statement in C


in this C-code fragment:

void func(void)
{
   int x=10;
   if (x>2)
   {
      int y=2;
      //block statement
      {
         int m=12;
      }
   }
   else
   {
      int z=5;
   }  
}

when does x,y,z and m get allocated and deallocated from func stack frame ?


Solution

  • The actual allocation depends on your compiler, but many compilers allocate space on the stack at the beginning of the function and free it just before the function returns. Note that this is separate from when the variables are actually accessible though, which is just till the end of the block they are defined in.

    In your example, with optimization turned on, the compiler is likely not to allocate any space on the stack for your variables and simply return, since it can determine at compile time that the function doesn't actually have any effect.