The new ?? and ??? operators
Arlen Albert Keshabyan
arlen.albert at gmail.com
Mon Sep 24 01:02:13 PDT 2007
Stewart Gordon Wrote:
> "Arlen Albert Keshabyan" <arlen.albert at gmail.com> wrote in message
> news:fd611h$4co$1 at digitalmars.com...
> > It would be the sugar syntactic to add '??' operator to D.
> > Consider the example code:
> >
> > string error_message = getErrorMessage() ?? "no errors";
> > A a = x.getPreparedAObject() ?? y.getPreparedAObject() ?? new A();
> >
> > This operator is supposed to do the same thing as C# does: lvalue
> > evaluates to the first non-null value or to null if all rvalues
> > contains null.
>
> So effectively, it works like || in JavaScript and the like. I guess the
> return type of a ?? expression would be determined by the same rules that
> govern that of a ConditionalExpression. The expression would evaluate to
> the first subexpression whose value when implicitly converted to a boolean
> is true. Otherwise ... to the .init of the return type?
>
> > This operator might be extended to '???' to evaluate to a value
> > that conforms to some conditions. The lvalue gets the first rvalue
> > that evaluates to true (evaluation goes from left to right). If no
> > conditions evaluates to true then the lvalue stays unchanged. If
> > no conditions are given explicitly then those conditions evaluates
> > to true (so, the best place for them is at the end of a sequence).
> <snip>
>
> I don't really like this:
> - It would cause the semantics of the = operator to depend on the form of
> the RHS.
> - What if the ??? expression isn't the RHS of an = operator?
> - The null case of this operator doesn't match semantically as they're
> normally expected to. (I'm not sure if there's any better way to word
> this.) To see what I mean, compare the meanings of
>
> a = b ??? c ??? d;
> a = b ??? c;
> a = b;
>
> Stewart.
>
> --
> My e-mail address is valid but not my primary mailbox. Please keep replies
> on the 'group where everybody may benefit.
>
If you'd read my first post carefully you'd never ask the question like this.
> a = b ??? c ??? d;
> a = b ??? c;
> a = b;
the conditions must be explicit (!). Inexplicit conditions always evaluates to TRUE despite types involved in conditions. So, you will got the following:
> a = b ??? c ??? d;
a = b; //any type, even boolean
> a = b ??? c;
a = b;
> a = b;
a = b; //so no ??? ternary operator. Treated just like no (?:) operator :)
bool a = true
bool b = true
bool c = false
bool d = true;
a = b != true ??? c != false ??? d == false ??? false;
now a == false because no conditions evaluates to true except for the last one 'false'. Yes, 'false' evaluates to true :) so it's assigned to the 'a' variable.
More information about the Digitalmars-d
mailing list