heap/stack memory allocation

Hi, just a quick question, when you define local variables inside a branch inside a function, are they allocated on the stack when that function is called, or are they only allocated if the branch executes, on the heap?

some code to clarify:

1
2
3
4
5
6
7
8
9
void somefunc()
{
	int someint; //this is allocated on the stack afaik

	if (somecondition)
	{
		int anotherint; //how is this allocated?
	}
}
AFAIK everything is allocated on the stack when the function is called. However it is initialized when that branch is taken (here that means nothing, but for a complex type like string it could be significant).

The flip side of that is that the compiler might be able to "recycle" stack space as an optimization:

1
2
3
4
5
6
7
8
9
10
11
void func()
{
  if(foo)
  {
    int a;
  }
  if(bar)
  {
    int b;
  }
}


Since a and b are never in scope at the same time, the compiler could (in theory) use the same stack space for each of them.
Stack, when the function is called. Note, however, that the constructor is only called when the declaration is reached.
Last edited on
thanks guys
Topic archived. No new replies allowed.