BlackStone Posted December 28, 2004 Posted December 28, 2004 Is it better to declare a variable outside of a loop, or does it not matter (performance wise)?? int start = 0; int end = size - 1; while (start <= end) { // Put it here or outside the block?? int middle = (start + end) / 2; .... } Quote "For every complex problem, there is a solution that is simple, neat, and wrong." - H. L. Mencken
Administrators PlausiblyDamp Posted December 28, 2004 Administrators Posted December 28, 2004 Performance wise it should make very little difference, from a code point of view though if the variable is only used within the block then declaring it within the block makes the code's intention that bit clearer and allows the compiler to enforce the variable scope. Quote Posting Guidelines FAQ Post Formatting Intellectuals solve problems; geniuses prevent them. -- Albert Einstein
Tygur Posted December 28, 2004 Posted December 28, 2004 I would say that any change in performance is negligable, if it's even there. The variable will still live until the procedure ends no matter where you declare it. It doesn't die once you leave the block, and it'll still have the same value if you reenter it. Quote
BlackStone Posted December 29, 2004 Author Posted December 29, 2004 I thought that space is made on the stack for the variable each time the block is entered. So, basically the variable just has scope in the block, but the variable is created once the procedure is called (Is that right)? Quote "For every complex problem, there is a solution that is simple, neat, and wrong." - H. L. Mencken
Tygur Posted December 29, 2004 Posted December 29, 2004 I don't know when the variable is created. I suppose it's possible that it might not be created until the block is entered. That's kind of difficult to test. But the variable does live after you leave the block. Here's Microsoft's documentation on the matter: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcn7/html/vaconvariablescope.asp Quote
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.