In C++ you should declare variables as late as you can (that is, as deep in scope as you can).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
// old C style
void function()
{
Type1 a, b, c;
Type2 d;
if (/* ... */)
{
// use a
// use d
}
else
{
// use b
// use c
// use d
}
}
|
// C++ style (and modern C style)
void function()
{
Type2 d;
if (/* ... */)
{
Type1 a;
// use a
// use d
}
else
{
Type1 b, c;
// use b
// use c
// use d
}
} |
The reason for using the C++ style is that there's a possible extra cost for declaring variables: when
Type1 is a
class/
struct that has a constructor, whenever you declare a
Type1 variable (called object) a function is called for it (the
Type1 constructor). Function calls are expensive, so you'll waste time creating objects that you may not use.
In the example above, the only variable that is used regardless of the
if() condition will be
d
, while the others can (and should) be put into deeper scope.
If you are programming in C, simply choose whichever style makes your code easier to read. I personally prefer the C++ style (mostly out of habit). You may prefer the old C style, because your code won't be cluttered with declarations, and if you want to see what the type of a local variable is, you'll always find it at the beginning of the function.