Optional braces

Timon Gehr timon.gehr at gmx.ch
Sun Aug 21 14:43:28 PDT 2011


On 08/21/2011 11:02 PM, Nick Sabalausky wrote:
> "bearophile"<bearophileHUGS at lycos.com>  wrote in message
> news:j2rh7g$2tfq$1 at digitalmars.com...
>>
>> To this innocent-looking D code, do you see the problem?
>>
>> void foo(Pair[] sol) {
>>     if (isSolution(sol[$-1]))
>>         if (!best.length || sol.length<  best.length)
>>             best = sol.dup;
>>     else
>>         foreach (next; alternatives(sol[$-1]))
>>             if (!canFind(sol, next))
>>                 foo(sol ~ [next]);
>> }
>>
>
> That's why I always use braces to avoid the construct "if(cond) stmt;
> if(cond) stmt; else..."
>
>>
>> There is a situation where I'd like D to require braces:
>> http://d.puremagic.com/issues/show_bug.cgi?id=4375
>>
>
> That's a fantastic idea. It basically checks exactly what I've been relying
> on convention for.
>
> *Only* potential problem I see with it is if someone wants to do this:
>
> if(blah blah blah)
>      if(useFoo) foo(); else bar();
> else
>      ...
>
> That's fairly sensible code. Although I admit I've never come across a
> situation where I actually wanted to do that. So personally I wouldn't mind
> giving up the ability to do that.
>
>

Well, it would not have to be disallowed. The rule could be like this:

Parse with the normal dangling else rule. If an if statement without an 
else clause is found, examine the then clause. If the then clause is an 
if statement with an else clause, error.

So if(c1)if(c2) x; else y; would be disallowed, but
if(c1)if(c2) x; else y; else z; would be allowed.








More information about the Digitalmars-d mailing list