Unused variables, better as error or warning?
bearophile
bearophileHUGS at lycos.com
Fri Aug 20 14:28:39 PDT 2010
Walter Bright:
> I detest warnings because they make the language rules "fuzzy". Code should be
> legal or illegal. Wishy-washy warnings make code non-portable because different
> compilers implement different warning.
I remember this problem you have explained in past.
In normal C code (not generated code and not while you debug) if you define a variable and then you don't use it then the compiler usually removes it and nothing of value is lost. And not using a variable is accepted by the C standard, so it can't be an error in C.
On the other hand, in a hairy C program of mine I have defined a counter variable, and then I have forgotten to use it, the unused variable warning given by GCC has given me a hint, and I have quickly fixed the code in few seconds.
So such situation is not an error, but it's a code smell (http://en.wikipedia.org/wiki/Code_smell ). Programming is not a binary thing, sometimes what you do is a symptom of a possible hidden problem (or a sign of correct but lazily written code, or correct code that in successive changes may develop a bug). But some times you want to break those conventions, despite they smell. Warnings probably are fuzzy because the programming reality is fuzzy.
If D will become successful then surely people will write a lint able to spot unused variables, it's a basic operation, and it's useful especially if the compiler can't do it.
The alternative is then to do as I think Go has done, and turn unused variables into errors. And then you need a way (like a pragma) to locally disable this error when you are debugging (and this is not nice), or when you generate code automatically (this is acceptable).
Another possible solution is to define uninitialized variables as errors only when D code is compiled in optimized build. This probably solves the problem with such spurious errors while debugging (you probably don't debug your code compiling in optimized mode). I think DMD is already doing something like this for used of uninitialized class instances, that are caught only if you compile code with -O.
Bye,
bearophile
More information about the Digitalmars-d
mailing list