Variable no-shadowing problems

Chris Miller chris at dprogramming.com
Fri Dec 22 15:53:26 PST 2006


To those not sure what shadowing means, here is an example of variable  
shadowing:
    int i;
    {
       int i;
    }
The inner `i` variable shadows the outer one.


D has made such shadowing illegal and flags it as an error. I'm against  
this restriction, but I have a compromise.

I am proposing a `shadow` keyword be added to D. Actually, the general  
idea is from someone else from #D IRC chat, but I have several reasons why  
explained below.

1) Accidentally shadowing a variable. If this happens you will have to go  
back and manually fix up all uses of the shadowed name, which has a very  
high chance of error. Forget to fix one and it goes by silently; bug. Or,  
simply add `shadow` to its declaration, avoiding tedious, error-prone  
fixing, and make people aware of what's going on.

2) Adding code. You can simply add a { } block and declare at will. With  
no shadowing, I am tempted to append random numbers to my variable names  
so I don't run into this, or moreso tempted to reuse variable names like  
is popular from C, as in declare once at the top of the function and reuse  
the variable for different things.

3) Code generators emitting D source code. They may not wish to keep track  
of such shadowing and could simply mark all declarations as `shadow`.


Notes:

`shadow` does not allow redeclarations in the exact same scope (although  
perhaps it could).

As for reason (1), if you are personally against shadowing, you are not  
forced to use the keyword and can continue treating it how it is done now.

- Chris



More information about the Digitalmars-d mailing list