#140730 - keldon - Wed Sep 19, 2007 4:19 pm
If your compiler supports it, what are your thoughts on scope variables (as shown below). And if you had to choose one approach to use for the rest of your life (if the compiler supports it) then which one and why?
Code: |
for (...)
{
int scope_var;
...
}
|
vs
Code: |
int scope_var;
for (...)
{
...
}
|
#140731 - gauauu - Wed Sep 19, 2007 4:43 pm
I would always put variables in the most limiting scope possible. The more limited the scope, the less likely you are to make a scope-related mistake. Is there some advantage to putting it in the larger scope if you don't intend to use it in that larger scope?
There's probably some exception to my "always" but I can't think of one now.
#140732 - kusma - Wed Sep 19, 2007 4:45 pm
The first one (this is guaranteed to be supported by the C standard AFAIK), since it limits the availability of the symbol, so you only get it where you actually plan to use it.
#140733 - keldon - Wed Sep 19, 2007 4:46 pm
Well I generally do the same, but there's an exception to every rule - unless this is the exception to there being an exception >_>
#140737 - sajiimori - Wed Sep 19, 2007 5:24 pm
I'm not aware of any exceptions to this rule.
#140798 - gmiller - Wed Sep 19, 2007 10:20 pm
The first one must create the variable for the loop to execute and remove it when the loop exits, where as the 2nd one the variable is already in existence when the loop starts. Depending on the compiler optimization the cration could be as simple as allocating a register to the variable or as complex as moving the stack pointer to hold the data. The creation of the variable on the stack requires processing that might be more than you want if the loop is in code that gets called many times. Optimization prior to testing in this case could be a waste of time. It is easy to make assumptions about what is slow or fast in a vacuum but where and how the code is used usually has more influence.
One of my co-workers who now teaches optimization wrote an article on this:
http://www.gamasutra.com/view/feature/1879/the_top_10_myths_of_video_game_.php