Scope of variables

Jonathan M Davis jmdavisProg at gmx.com
Fri Jun 24 18:42:42 PDT 2011


On 2011-06-24 17:39, Adam D. Ruppe wrote:
> >    void baz(local int k) {
> >    
> >        void inner(local int k) {}
> >    
> >    }
> 
> This is unneeded. By declaring a local variable, it's
> *obviously* local - there's no point in saying local again!
> 
> Now, I've forgotten that I had a variable declared before, but
> adding more stuff to the argument list wouldn't change anything,
> because if I was looking at the argument list, I would have realized
> the local variable was there anyway!
> 
> If D was a bad language that allowed implicit variable definitions,
> it might make sense to do this, but we already declare all vars so
> it adds nothing.
> 
> > void foo(int i) {} // hiding global variable
> 
> This is a good thing because you can reason about it locally. If
> you declare a variable locally, you know it is going to work.
> 
> What I've taken to doing is if I definitely want to access a
> class var, I'll just write this and use the dot to get to a global.
> 
> That way, it's always clear what's going on without looking
> back at the function definition.

That's why a lot of people typically use a different naming scheme for member 
variables (e.g. prepending them with _ or m_). As long as you're smart about 
naming, it's really not a problem.

> I don't want that to be required though.

Yeah. That would not be fun. As it is, there are a variety of ways that you 
can go about differentiating between globals, locals, and member variables. 
There's no need for the compiler or language to get into it any further than 
they already do. Being too strict about stuff like that would get very 
annoying.

- Jonathan M Davis


More information about the Digitalmars-d mailing list