Sign in to follow this  
nsto119

How do variables declaired in loops work?

Recommended Posts

What I mean is... do they go out of scope (and get taken off the stack) each time the loop reiterates? Is it generally a better idea to declare variables outside loop and initialize them inside the loop?

Share this post


Link to post
Share on other sites
The vagaries of loops and scoping rules depend on the particular language you're talking about. In general, anything between braces has its own scope; once you reach a "}", the scope matching the corresponding "{" is wiped clean and you lose any references to things inside.

Hope that helps,
-- k2

Share this post


Link to post
Share on other sites
However, you should also keep in mind that even a blind and deaf compiler with a broken optimizer will almost certainly preserve the variables in an effort to keep them from being created/destroyed again and again and again if it thinks that this would even marginally effect preformance. Don't worry about it, let the compiler work with you, instead of using your own solutions of questionable worth [grin]

At code level, I'd say that K2 is perfectly correct, however, once the compiler turns things into optimized machine code, there aren't really any guarentees about exactly what it will do in a case like this, other then that it will run your code prefectly, and it will do it optimized.

Share this post


Link to post
Share on other sites
Quote:
Original post by nsto119
Is it generally a better idea to declare variables outside loop and initialize them inside the loop?


It depends, for built-in variable type, it is generally prefered to declare the variable inside the loop. But for classes/structures it maybe slightly different:

If your need to use every member variables in your class _and_ the cost of constructing/destructing your object is small _and_ the member variables' values are refreshed each loop then it can be declared inside the loop. I.e: struct Vector3D has it's members values changed each time repeating the loop. Chances are all the required variables maybe manipulated in the CPU registers, they'll be faster than having to fetch from the stack.

Otherwise, if only some of member variables in your class are changed while looping, the rest remains intact then it should be declared out side the loop or in the initialization of for loop to reduce the cost of moving the same values over and over again.

Both of them are from programmer's standpoint, after compiler optimizations I don't know for sure what they'll be [wink].

Hth

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this