Disallowing ?:?: syntax

Nick Sabalausky a at a.a
Mon Jan 5 06:53:52 PST 2009


"Miles" <_______ at _______.____> wrote in message 
news:gjst46$2hh1$1 at digitalmars.com...
> bearophile wrote:
>> My little proposal for D is to turn the following into a syntax
>> error, to avoid possile programmer mistakes (so the programmer must
>> put parentheses here to make it compile):
>>
>> x ? y : a ? b : c
>
> The ternary operator is not ambiguous, I see no need for making it an
> error. I have used such constructs very often, with no problem:
>
> writefln("Printer is %s.",
> status == OFFLINE      ? "offline"      :
> status == ONLINE       ? "online"       :
> status == CHECK        ? "out of paper" :
> status == ONLINE_CHECK ? "on fire"      :
> "unknown status");
>
> That would become a real mess of parenthesis.

This makes my highly DRY-oriented mind think:

While ?: is an expression-based counterpart to the statement-based 
if...else, maybe we could use a similar expression-based counterpart to 
switch? (I think I've seen such a thing in hardware description languages)

--------------------
writefln("Printer is %s.",
status ??   // Purely illustrative syntax
OFFLINE => "offline" ::
ONLINE => "online" ::
CHECK => "out of paper" ::
ONLINE_CHECK => "on fire" ::
default => "unknown status");
--------------------

Although, I've often created re-usable lookup tables to handle that sort of 
thing:

--------------------
char[] getPrinterStatusStr(uint code)
{
    // Somthing like this, I forget the exact syntax and nuances. D's array 
literals are a PITA.
    char[][uint] printerStatusCodeToStr =
    [
        OFFLINE : "offline",
        ONLINE : "online",
        CHECK : "out of paper",
        ONLINE_CHECK : "on fire",
    ];

    return (code in printerStatusCodeToStr)?
        printerStatusCodeToStr[code] :
        "unknown status";
}
writefln("Printer is %s.", getPrinterStatusStr(status));
--------------------

But the ??=>:: (again, purely illustrative syntax) would be a nice 
alternative to have at my disposal. And it would make writing 
getPrinterStatusStr much nicer.

Back to the original ?:?: issue: If I were to ever chain ?:'s, Miles's 
example above is the only time I ever would feel comfortable omitting any 
disambiguating parens. If we got a ??=>:: (or something like it), then I 
would agree with making ?:?: illegal without disambiguating parens. But 
without a ??=>::, I think Miles's example provides a compelling reason to 
keep the ?:?:. 





More information about the Digitalmars-d mailing list