Notes IV
Oskar Linde
oskar.lindeREM at OVEgmail.com
Sun Jan 27 13:54:56 PST 2008
bearophile wrote:
> Oskar Linde:
>> A working compromise would be to disallow only "ambiguous" else
>> clauses, forcing one to add {} in those cases only.
>
> I like this idea, can you show few examples? If it's a good compromise then it may be used in D 2.x...
D, C and many other languages have grammar rules such as
S : if ( E ) S else S
S : if ( E ) S
S : other ;
under such rules, a program such as
if(a) if(b) f1(); else f2();
could have two ambiguous interpretations:
1. if(a) { if(b) f1(); else f2(); }
2. if(a) { if(b) f1(); } else f2();
D (and many other languages) disambiguate by always picking
interpretation 1. The else always matches the most recent if.
One could instead flag this as an error, requiring the addition of
braces whenever an ambiguous dangling else is found. For example:
void main() {
if (a)
if (b)
f1();
else
f2();
}
test.d:5: error: ambiguous 'else' found. Please disambiguate with braces {}.
To resolve this error, one would have to add one pair of braces. Either:
void main() {
if (a) {
if (b)
f1();
} else
f2();
}
Or:
void main() {
if (a) {
if (b)
f1();
else
f2();
}
}
I hope I've made it a bit clearer.
Regards,
--
Oskar
More information about the Digitalmars-d
mailing list