-4

if I have few local variables in function like -

void fun()
{
  int a,b,c,d,e,f,g;
} 

Does compiler allocate memory for each variable one after another ? if yes why doesn't compiler reads all variables at once and then allocate memory for them at one shot ?

  • 5
    depends on compiler, optimization options etc. In most cases this code would result in single stack frame pointer value updated. – Hcorg Jun 30 '15 at 11:23
  • https://stackoverflow.com/questions/1102049/order-of-local-variable-allocation-on-the-stack – Cory Kramer Jun 30 '15 at 11:25
  • https://stackoverflow.com/questions/8614131/how-is-memory-allocated-for-local-variables – Cory Kramer Jun 30 '15 at 11:25
  • 2
    "why doesn't compiler reads all variables at once and then allocate memory for them at one shot ?". That's roughly what most compilers do. What makes you think the memory is not allocated at one shot ? – Jabberwocky Jun 30 '15 at 11:31

1 Answers1

7

The compiler doesn't allocate memory for any of them. The difference between your source code and your final executable is more complicated than that. In short, though, if these variables actually end up physically existing on the executing computer (which is by no means certain: lots can be optimised away!), their size will just go towards the size of the stack frame, which is largely "constructed" simply by virtue of how far the stack pointer is incremented whenever this scope is entered/left.

In that sense, the compiler will "allocate memory for them at one shot". But it basically won't. :-)

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
  • *votes up* this answer deserves one googolplexian of upvotes as it discovers a hidden secret unspoken – Imobilis Jun 30 '15 at 11:59
  • 2
    Note that since these are plain ints, the compiler more likely decides that these variables should be allocated in CPU registers. Same principle though, the compiler doesn't "allocate" them but rather creates a machine code instruction "store a in register r" as part of the program. – Lundin Jun 30 '15 at 12:00
  • @Lundin very low level-related reasoning, I like that. I think they will be stored automatically in the program's internal memory so yes. Do you have e-mail? – Imobilis Jun 30 '15 at 12:06