6

Im trying to figure out what is the best practice when initializing certain variables... My code looks like this at the moment:

int nHexCount = 0;
int prevState = sc.state;

bool bOnlySpaces = true;
bool bIsValidLabel = true;
bool bIsHotstring = false;
bool bIsValidName = true;
bool bIsValidExpStart = false;                         

bool fInExpression = false;
bool fInStringBlock = (sc.state == SCE_AHKL_STRINGOPTS || sc.state == SCE_AHKL_STRINGBLOCK);

for (; sc.More(); sc.Forward()) {

    if (sc.atLineStart) {
        if (!fInStringBlock && sc.state != SCE_AHKL_COMMENTBLOCK)
            sc.SetState(SCE_AHKL_DEFAULT);

        // Reset Status
        prevState = sc.state;

        bOnlySpaces = true;
        bIsValidLabel = true;
        bIsHotstring = false;
        bIsValidName = true;
        bIsValidExpStart = false;

        fInExpression = false;
    }

...

So as you can see most of these variables are reset each time my program finds a new line in the edit component i am working on...

The question would be:

Is it better programming practice declaring and initializing all those variables inside the for loop or should i leave it like it is at the moment?

RaptorX
  • 331
  • 1
  • 9
  • 19

1 Answers1

12

You should always reduce the scope of the variables as much as possible. This will improve the maintainability of your code, and reduce the chance of bugs.

// bad
int i, j, k;
k = 0;
for (i = 0; i < X, ++i)
{
  j = foo(i);
  k += j;
} 

bar(k);

... vs ...

// better
int k=0; // needs scope outside loop
for (int i = 0; i < X, ++i)
{
  int j = foo(i);
  k += j;
} 

bar(k);
Roddy
  • 66,617
  • 42
  • 165
  • 277
  • 1
    What about performance by the way..? Won't it be costly initializing it every time? – sashkello Nov 01 '12 at 22:31
  • 3
    @sashkello: For primitives: no. For more complex stuff: probably not. – Mooing Duck Nov 01 '12 at 22:32
  • I have refrained myself from changing them exactly because of this reason. Is there any overhead because of that? -- EDIT just read the answer above. – RaptorX Nov 01 '12 at 22:32
  • 7
    There can be no overhead. These are automatic variables, meaning they already exist in the stack. It's not like they're allocated on every iteration of the loop. Declaration and initialization has exactly the same cost as assignment. The exception are complex types where declaration involves calling a constructor that does some extra work. – Nikos C. Nov 01 '12 at 22:39
  • 7
    @sashkello: Premature optimization is the root of all evil :) Compilers are pretty smart now; there's a good chance that (especially with primitives or standard types) the compiler will do what it can to optimize any additional overhead away (though in this specific case there happens to be none). – Robert Mason Nov 01 '12 at 22:50