Gaijinco wrote:
> I have always felt that you should only declared variables as needed,
> and implicitily it seems many authors to encourage it, but the other
> day a friend told me that declaring variables inside a loop wasn't good
> practice, something like:
>
> for(int i=0; i<size-1; ++i){
> int aux = array[i];
> array[i]=array[i+1];
> array[i+1]=aux;
> }
>
> should be written like:
>
> int aux;
> for(int i=0; i<size-1; ++i){
> aux = array[i];
> array[i]=array[i+1];
> array[i+1]=aux;
> }
>
> What do you think? Thaks!
Your friend might think that the first code is slower. In some few similar
cases it might indeed be slower. You shouldn't worry about that.
Tell your friend that premature optimization is the root of all evil. The
most important resource to optimize is programmer time. Programmers must
write clean code first, because it's easy to make beautiful code fast than
fast code beautiful.
After your for loop ends, aux's only meaning is "the last variable in the
array". Subsequent statements should not rely on the for loop "leaking" its
last aux value out. If they want the last value in the array, they should
get it themselves. They should decouple as much as possible from the rest
of your program, including the statements just before them.
Always give any identifier the narrowest scope and access possible. Don't
use global variables or public data members. Never create a variable
without giving it an initial value. Put all these rules together, and you
have many reasons to put int aux inside the loop.
--
Phlip
http://www.greencheese.org/ZeekLand <-- NOT a blog!!!