Rainer Deyke wrote:
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.

Not necessarily. The optimizer uses a technique called "live range analysis" to determine if two variables have non-overlapping ranges. It uses this for register assignment, but it could just as well be used for minimizing stack usage.

Reply via email to