My instructor once told me that I should not define a variable inside a loop, but I honestly still do not understand why.What are the disadvantages of that?Could any body explain that to me?
Is it good to define a variable inside a loop?
c++;programming practices;performance;initialization;declarations
It's not a problem to define a variable within a loop. In fact, it's good practice, since identifiers should be confined to the smallest possible scope.What's bad is to assign a variable within a loop if you could just as well assign it once before the loop runs. Depending on how complex the right-hand side of the assignment is, this could become rather expensive and might even dominate the run time of the loop. If you write a loop that uses the same computed value in all iterations, you should definitely compute it above the loop - that is more important than minimizing its scope.To clarify: as long as compute() always returns the same value, thisint value = compute();while (something) {    doSomething(value);}is smarter than this:while (something) {    int value = compute();    doSomething(value);}