Missing compiler warning?

bearophile bearophileHUGS at lycos.com
Fri Oct 18 09:32:32 PDT 2013


Chris:

> I had a stupid bug:
>
> class Base {
>   SomeStruct someStruct;
>   // ...
> }
>
> class BaseSub {
>   // ...
>   override {
>     public void doThis() {
>       auto someStruct = checkSomething("input"); // Bug is 
> here, of course,
>                                                  // a leftover 
> from old code
>     }
>   }
>
>   private void doSomethingElse() {
>     if (someStruct.hasValue) {
>        auto val = someStruct.value; // Segmentation fault (core 
> dumped)
>        // ...
>     }
>   }
>
>   private auto someCheck(string input) {
>     return SomeStruct(input);
>   }
> }
>
> dmd 2.63
>
> SomeStruct is declared outside the class.
>
> It compiled and dmd didn't say anything about "local variable 
> declaration someStruct is hiding class variable someStruct."


If I understand correctly, you are suggesting to generate a 
warning here:


class Foo {
     int x;
     void bar() {
         auto x = 1; // ?
     }
     void spam(int x) { // ?
     }
}
void main() {}


Currently D doesn't give an error or warning if in a method you 
declare a local variable with the same name of a instance member. 
This is indeed a source of bugs and I have had similar problems. 
Generally D prefers to minimize the number of warnings, so 
according to the D style that should become an error.

I presume D is designed this way for compatibility with Java 
code. But I don't like much this part of the D design. In other 
cases (with for/foreach loops, the with statement) D has chosen 
to break the C++ way and introduce a variable shadowing error.

Bye,
bearophile


More information about the Digitalmars-d mailing list