Home > Net >  cppcheck suggests to reduce scope of variable, should I?
cppcheck suggests to reduce scope of variable, should I?

Time:02-16

So I have something like this

    int age;

    for (auto person : persons) {
        age = std::stoi(person[0]);

        /* Do other stuff with age in this loop*/
    }

Other than style, are there any performance benefits to declaring int age = std::stoi(person[0]); inside the loop?

CodePudding user response:

Since you have used the age variable only inside the for loop, you may reduce its scope and declare it inside the for loop only. That way, the compiler doesn't have to remember the variable once you're done with it in the loop.

You should declare it outside the loop only if you intend to use it outside as well.

CodePudding user response:

are there any performance benefits

Because of the "as-if" rule, it's reasonable to assume that there is no performance difference between two equivalent ways of declaring the same variable.

  • Related