Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing variable in loop [duplicate]

Tags:

c++

for-loop

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?

like image 689
RaptorX Avatar asked Nov 01 '12 22:11

RaptorX


1 Answers

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);
like image 146
Roddy Avatar answered Nov 15 '22 10:11

Roddy