local variables & memory

Started by
1 comment, last by Rocket05 21 years, 4 months ago
how are local variables (any variable not global or dynmically allocated) handled in c++? every time a function is called, must it reallocate the memory for its local variables and release them after returning to the calling function? im just wondering whether or not its a good idea to avoid large amounts of local variables in my functions, for speed''s sake. all help is greatly appreciated
"I never let schooling interfere with my education" - Mark Twain
Advertisement
Local variables are allocated on the stack, which has effectively no allocation time (seeing as stack operations are performed for changing function context anyways).
There are soooo many great interview questions in this, but they''re more implementation questions than C questions so they''re almost unfair. e.g.:
Which is faster?
1)

  void f1 (){  int a;  return;}void f2 (){  int a[4000];  return;}  

(answer = they''re the same)

2)

  void f1 (){  char s[400];  for (int i=0; i<100000; ++i)  {      someFunc (s);  }}void f2 (){  for (int i=0; i<100000; ++i)  {     char s[400];     someFunc (s);  }}  

(answer = they''re the same)

The key is this: a C/C++ compiler calculates the sizeof all the locals that may possibly be used in a function, regardless of branching, and allocates room for all of them at once at the beginning of the function call by moving the stack pointer to allocate for that. (Some smart compilers _could_ have variables that are in orthogonal scopes share space--haven''t checked if this really happens myself).

This topic is closed to new replies.

Advertisement