Module level variable shadowing

H. S. Teoh via Digitalmars-d digitalmars-d at puremagic.com
Wed Jun 25 16:07:06 PDT 2014


On Wed, Jun 25, 2014 at 11:03:14PM +0000, bearophile via Digitalmars-d wrote:
> While I try to minimize the number of module-level variables in D
> code, sometimes they are present, and sometimes I have problems (bugs)
> caused by unwanted shadowing of global names (or sometimes more
> generally, names from outer scopes, but this is less common):
> 
> 
> int x = 1;
> // ...
> void foo() {
>     // ...
>     int x = 2;
>     // ...
>     writeln(x);
> }
> 
> 
> Can't we find a way to avoid/find such kind of bugs? (It's not a
> problem of mutability, because the same problem happens with immutable
> variables.) I have hit this bug several times.

My advice is to avoid module globals unless absolute necessary. A whole
class of problems are avoided that way.


> The simplest way to avoid that kind of bugs is give a "shadowing
> global x error" (similar to the shadowing errors D gives with foreach
> and with statements). But this breaks most existing D code.
[...]

If you want to refer to a module global, write .x instead of x.


T

-- 
Тише едешь, дальше будешь.


More information about the Digitalmars-d mailing list