Null references redux

Rainer Deyke rainerd at eldwood.com
Sun Sep 27 02:58:54 PDT 2009


Jeremie Pelletier wrote:
> void bar(bool foo) {
>     if(foo) {
>         int a = 1;
>         ...
>     }
>     else {
>         int a = 2;
>         ...
>     }
> 
> }
> 
> is the stack frame using two ints, or is the compiler seeing only one? I
> never bothered to check it out and just declared 'int a = void;' at the
> beginning of the routine to keep the stack frames as small as possible.

OT, but declaring the variable at the top of the function increases
stack size.

Example with changed variable names:

  void bar(bool foo) {
    if (foo) {
      int a = 1;
    } else {
      int b = 2;
    }
    int c = 3;
  }

In this example, there are clearly three different (and differently
named) variables, but their lifetimes do not overlap.  Only one variable
can exist at a time, therefore the compiler only needs to allocate space
for one variable.  Now, if you move your declaration to the top:

  void bar(bool foo) {
    int a = void;
    if (foo) {
      a = 1;
    } else {
      a = 2; // Reuse variable.
    }
    int c = 3;
  }

You now only have two variables, but both of them coexist at the end of
the function.  Unless the compiler applies a clever optimization, the
compiler is now forced to allocate space for two variables on the stack.


-- 
Rainer Deyke - rainerd at eldwood.com



More information about the Digitalmars-d mailing list