CppCheck. The scope of the variable can be reduced (and loop)

peter55555 picture peter55555 · May 12, 2014 · Viewed 12.2k times · Source

CppCheck finds me some findings like: "The scope of the variable 'x' can be reduced".

What if I have this situation:

int x;
for (int i = 0; i != 10; ++i)
{
    x = someFunction();

    // ... I use x variable here
}

I think my code is OK. What do you think? Should it change to something like that?

for (int i = 0; i != 10; ++i)
{
    int x = someFunction();

    // ... I use x variable here
}

In the second code a variable x is defined for all iteration... Isn't not ok (not optimal), I guess..

Answer

Vlad from Moscow picture Vlad from Moscow · May 12, 2014

If variable x is not used outside the loop then the second approach is much better. And there is not the slightest problem with the optimization of the code. The memory for the variable is allocated only once in the loop.