Scope/block behaviour
Andrei Alexandrescu
SeeWebsiteForEmail at erdani.org
Thu Aug 19 06:54:57 PDT 2010
On 08/19/2010 07:06 AM, Eduardo Cavazos wrote:
> Hello,
>
> I was surprised that these seem to not be allowed in D:
>
> void main ()
> {
> auto a = 20 ;
>
> {
> auto a = 30 ;
> }
> }
>
> void main ()
> {
> { int f0 () { return 10 ; } }
>
> { int f0 () { return 20 ; } }
> }
>
> Perhaps I missed something in the FAQ.
>
> Is there anywhere (manual or TDPL) I can read up on this language design
> decision? What other contemporary (or classic) languages feature this
> behaviour? Scheme and C both allow the above.
>
> It seems like this would be something that might be nice for certain
> shops to enforce via a compiler switch, but not on by default.
>
> Ed
Raw text from TDPL:
However, it is
illegal to define a symbol that would mask a symbol in an enclosing
compound statement:
\begin{D-nocheck}
void main() {
auto widgetCount = getWidgetCount();
// Let's now open a nested block
{
auto widgetCount = getWidgetCount(); // /*[\codeError]*/
}
}
\end{D-nocheck}
\indexes{masking}%
As long as masking does not occur, it's legal to reuse the same symbol
in different compound statements:
\begin{D}
void main() {
{
auto i = 0;
...
}
{
auto i = "eye"; // Fine
...
}
double i = 3.14; // Fine too
}
\end{D}
\begin{D-expect}
\end{D-expect}
\indexes{masking, hiding, name hiding, modularity}%
The rationale of this setup is simple. Allowing global symbol masking
is necessary for writing good modular code that's assembled out of
separately compiled parts; you don't want the addition of a global
variable to suddenly render various innocent bystanders uncompilable.
On the other hand, enclosing-scope masking is useless as a modularity
device (as there's never a case of a compound statement spanning
multiple modules in~\dee) and most often indicates either an oversight
aspiring to become a bug, or a cancerous function that's grown out of
control.
Andrei
More information about the Digitalmars-d
mailing list