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?
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? |
|||||||||||||||||||||
put on hold as unclear what you're asking by GlenH7, durron597, Bart van Ingen Schenau, gnat, Ixrec 21 hours agoPlease clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question. |
|||||||||||||||||||||
|
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. |
|||||||||||||||||||||
|
Complex types have non-trivial constructors and destructors. Those will get called at the start and end of the loop (as it's initialized and goes out of scope). If the initialization is expensive like it needs to allocate some memory then that should be avoided. However for trivial types that is no problem. The allocation and deallocation itself is just adding and subtracting a value from the stack pointer. (which will get optimized out) |
|||
|
Well, his advice is slightly too simple (that's understatement).
|
|||
|