On 2012-06-17, BartC <> wrote:
>
> But what happens when the code defines a variable two pages into a function,
> but you happen to be reading some code using that same variable four pages
> into the function! Where do you go to find the definition? At the start of a
> function is usually a good place! You don't always know that a variable is
> only used once.
>
> And with blocks having their own scope (?) the same name can be used more
> than once with different definitions; even more confusing.
That's precisely the whole point: if you declare a variable inside
a block you DO KNOW that it is only used there and if the identifier
appears elsewhere it must be referring to something else. There
are many times you want a local variable for a short amount of time
and that's it. If you declare the variable in the appropriate
block you don't need to mentally keep track of the variable either
before or after that block. Fewer variables to keep track of
generally means fewer corner cases, fewer uninitialised or outdated
variables, and fewer dangling pointers, whether they are still
relevant or not.
One fairly common idiom that comes to mind would be along the lines of:
if (some_condition()) {
int retval = operation(object);
free(object);
return retval;
}
Why have an extra variable hanging around a whole function for
something so trivial? What is more, a variable like that is easily
identified by the compiler as being short lived and can be optimised
as such - put into a register or whatever. It knows that it doesn't
need to preserve its value because you happened to re-use the same
variable for something else later in the function.
--
Andrew Smallshaw