Declaring data types in loops

Take a moment to compare these two snips of code:

1
2
3
4
5
int x;
while(true)
{

}


1
2
3
4
while(true)
{
int x;
}


When you declare x in the loop, is x created every loop cycle? In other words, if you do something with x, will the data be deleted and just be created again? Or does that only work with the keyword static?

Also, if it DOES create it everytime, how slow can this make your program? Is it bad practice? Lots of times I only need a variable for a specific scope, so I don't want x to be seen by anything outside the while loop. but obviously the only way to do that is to declare it in the loop.
Last edited on
will the data be deleted and just be created again?

Yes.

how slow can this make your program?

Depends on the type. It is fast with int. It will be slow with complex types that do something heavy in their constructor/destructor.
In this case it probably don't slow you down anything at all because it should be able to reuse the same memory locations for x in all loop iterations and no constructor and destructor code has to run because it's an int.
Is it bad practice?

This is one of the cases where you have to make a tradeoff as a programmer. If x is not used/needed outside the loop scope, then yes, it generally better to declare it inside the loop. This ensures it's not used/misused outside the loop.

As other have said, the overhead is going to depend on the type of the object and the complexity of the initialization. For a simple int, the compiler will typically generate an increment of the stack pointer where x is declared and a decrement of the stack pointer at the bottom of the loop. Both very fast instructions. A good optimizing compiler will recognize that these instructions are invariant and will move them outside the loop, so you get the best of both worlds. Visibility of x is limited and the instructions are executed only once.

Worrying about this level of performance is generally unwarranted.

Topic archived. No new replies allowed.