问题
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