8 Dec 21:07
Re: req - block-local variables
> On Sat, 2007-12-08 at 10:03 +0100, Stefan Behnel wrote:
> > David McNab wrote:
> > > I'm wishing for the ability to declare cdef vars within blocks
> > > whose scope is confined to the block, just like in C - no
> > > 'leaking out'.
> >
> > That would be mainly of syntactical interest. While I understand
> > that it would be nice for readability to declare a name only in
> > the scope where it is supposed to be used, you would likely not
> > gain much performance-wise, as C compilers are pretty good in
> > figuring out the 'real' scope of a variable.
Something that is allowed in all versions of C is declaring new
variables at the top of a block, which can then be used only in that
block. One could say: move the variable to the top of the function or
method, as we've stated in the rest of this e-mail thread.
But, there is a situation that can be (ab)used in C in which this
cannot be done without some thought: it's possible to declare
variables with the same name in different blocks that do not have the
same type. For example (in C):
if (something == 0)
{
unsigned int i;
for (i = 0; i < something_that_is_unsigned; i++)
do_something1();
}
else
(Continue reading)
I think this is true most of the time, but not always. Even so,
I'm a fan of keeping things as local as possible. If one doesn't need
a variable until halfway down the function (or only within a single
if block) I'd rather declare it there than further up.
>> Variables don't have to be defined at the top of a function, they
>> just (currently) can't be defined inside blocks. This restriction
>> could be removed (with leaking) fairly easily and would solve
>> this issue. What are the drawbacks to doing this.
>> Greg, I'm cc'ing you because I'm guessing you had some reason to
>> explicitly dis-allow this. Comments?
>
> Well, the "with leaking" is kind of a clue. Various aspects of
> the code generation assume that function-local variables live for
> the whole lifetime of the function call and only need to be
> cleaned up at the end. Changing that would require some careful
> thought, and there doesn't seem to be any strong motivation to
RSS Feed