Archived

This topic is now archived and is closed to further replies.

local variables & memory

This topic is 5502 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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

Share this post


Link to post
Share on other sites
Local variables are allocated on the stack, which has effectively no allocation time (seeing as stack operations are performed for changing function context anyways).

Share this post


Link to post
Share on other sites
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).

Share this post


Link to post
Share on other sites