0

I'm currently reviewing a code, and there are many local variables in varying sizes.

Is declaring in increasing order of size the preferable one or vice versa.

Explain it with memory layout in either of scenarios.

Is memory allocated for the local variables based on order of declaration or on size.

int fun()
{

  struct *ptr;
  int var1;
  long double *ld;
  .
  .
  .
  .
}
Madhu
  • 61
  • 1
  • 9

3 Answers3

3

The best place to declare (and initialize) a local variable in C++ is right at the point where it's first needed.

The size of the variable should not be a consideration at all, unless you have specific evidence to the contrary.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
1

Compiler will reorder local variables as it sees fit, when it does optimizing. In short, order of variables in the same scope does not matter.

What is good idea though, is to declare local variables in the scope where it is used, for example:

void func() {
    //int i, j; // not here!
    for (int i = 0 ; i<10; ++i) {
       int j = func2(i);
       ...
    }
    // i and j below are different variables than i and j above
    // you can consider changing their names if they also have different meaning
    for (int i = 0 ; i<10; ++i) { 
       int j = func3(i);
       ...
    }
}

Though for good optimizing compiler, that likely will not matter from performance or memory footprint point of view (it will detect when variables are used anyway). It will still make the code more readable, and avoid mixing unrelated values in different scopes, thus protecting from some stupid bugs not caught by compiler warnings (because compiler doesn't know when you are accidentally forgetting re-initialization of re-used variable, but it will know if you forget to initialize a new variable).


Also, important thing when worrying about variables (or anything): remember to turn on warnings for compiler, like -Wall -Wextra for gcc. Also, using valgrind is good idea (if you can get your code to run on OS which has valgrind).

hyde
  • 60,639
  • 21
  • 115
  • 176
0

My approach is, that I declare local variables in the smallest possible scope, at the scope's beginning, e.g.

void foo()
{
    int local1 = 42;
    int local2 = bar(local1);

    if ( local2 != local1)
    {
        double local3 = double(local2)/double(local1);
        MyMemoryAllocatingObject mmao; // large memory allocation, deallocation in destructor

        baz(local3);
        bat(mmao);
    } // mmao memory gets freed here
}

For not-sophisticated compilers it helps optimization, for users it helps tracking the information. Plus, it helps keeping memory footprint as small as possible, because the locals go out of scope (sic!), i.e. their destructor is called.

ogni42
  • 1,232
  • 7
  • 11