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

c, c++, coding-style, cppcheck, performance

Solution

The position of an `int` declaration has no performance impact, so Cppcheck is right when raising this style issue. This style issue can be applied to non-trivial types as well,

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

    // ... I use x variable here
}    

since constructors tend to be as equally efficient as assignments. As of Version 1.65, Cppcheck seems not to distinguish between trivial and non-trivial types.

But don't blindly follow such style suggestions, there will be cases of non-trivial types where assignment is more efficient than construction. (As usual: if in doubt about performance, measure!)

Edit: a style consideration

The second variant is better in style as it combines declaration and initialization:

- This often saves you from writing (or reading) a comment that is not very meaningful.

- Sometimes you can also add `const`, which prevents you from accidental changes

Problem

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..

Original source