Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function and declaring a local variable

Just having an conversation with collegue at work how to declare a variables. For me I already decided which style I prefer, but maybe I wrong.

"C" style - all variable at the begining of function. If you want to know data type of variable, just look at the begining of function.

bool Foo()
{
    PARAM* pParam = NULL;
    bool rc;

    while (true)
    {
       rc = GetParam(pParam);
       ... do something with pParam
    }
}

"C++" style - declare variables as local as possible.

bool Foo()
{       
    while (true)
    {
        PARAM* pParam = NULL;

        bool rc = GetParam(pParam);
       ... do something with pParam
    }
}

What do you prefer?

Update The question is regarding POD variables.

like image 478
dimba Avatar asked Jul 06 '10 19:07

dimba


3 Answers

The second one. (C++ style) There are at least two good reasons for this:

  1. This allow you to apply the YAGNI principle in the code, as you only declare variable when you need them, as close as possible to their use. That make the code easier to understand quickly as you don't have to get back and forth in the function to understand it all. The type of each variable is the main information about the variable and is not always obvious in the varaible name. In short : the code is easier to read.
  2. This allow better compiler optimizations (when possible). Read : http://www.tantalon.com/pete/cppopt/asyougo.htm#PostponeVariableDeclaration
like image 188
Klaim Avatar answered Oct 05 '22 22:10

Klaim


If due to the language you are using you are required to declare variables at the top of the function then clearly you must do this.

If you have a choice then it makes more sense to declare variables where they are used. The rule of thumb I use is: Declare variables with the smallest scope that is required.

Reducing the scope of a variable prevents some types errors, for example where you accidentally use a variable outside of a loop that was intended only to be used inside the loop. Reducing the scope of the variable will allow the compiler to spot the error instead of having code that compiles but fails at runtime.

like image 21
Mark Byers Avatar answered Oct 05 '22 22:10

Mark Byers


I prefer the "C++ style". Mainly because it allows RAII, which you do in both your examples for the bool variable.

Furthermore, having a tight scope for the variable provides the compile better oppertunities for optimizations.

like image 39
James Curran Avatar answered Oct 05 '22 22:10

James Curran