Friday, September 16, 2005

Code Efficiency - Variable Scope Depth


I have a general question regarding code efficiency. In my workplace,
I have come across two different approaches to variable declarations
and scope.

One is to declare all function variables at the top of the function and
reuse the variables inside of loops, long condition handlers, etc.
>From a style perspective, this makes code difficult to read since its a
rule-of-thumb to declare variables as close as possible to their use.
However, the variables are allocated and intialized once.

The other scenario I've seen is for the programmer to literally declare
variables within 'while' and 'for' loops. Under the rules of C++, this
is safe because the variables will have loop scope. It is also
incredibly easy to read since the variables are right there when they
are used (which is just inside of the loop), and it doesn't have to be
traced towards the top of the function or even the top of the loop if
it is a long one. However, does the contant re-initializing hamper
efficiency of the program?

Calling to the coder community, what are you thoughts? Is it better
practice to take advantage of loop scope (block scope) or should all
variables be delcared outside of loops?

0 Comments:

Post a Comment

<< Home