Initializing variable in loop [duplicate]

无人久伴 提交于 2020-12-25 09:57:19

问题


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?


回答1:


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);


来源:https://stackoverflow.com/questions/13186476/initializing-variable-in-loop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!