The new ?? and ??? operators

Robert Fraser fraserofthenight at gmail.com
Sun Sep 23 14:54:58 PDT 2007


Arlen Albert Keshabyan Wrote:

> 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. 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).
> 
> For instance:
> 
> int codeval = getValue1() > 5 ??? getValue2() >= 4 ??? getValue3() != 0 ??? 1; // if no conditions are satisfied then codeval = 1 as a default value at last. There are no sane reasons to place it in the middle of the sequence.
> 
> int code = 7;
> code = 5 < 10 ??? 0 != 0; // this way, code = 7 (no conditions are satisfied)
> 

I have mixed feelings about the ternary operator. Nobody ever told me what it did, and I never saw it in any code when I was first learning to program, so consequently, when I finally saw it for the first time, I was baffled by it. Now that I understand it, I was using it quite often, but recently another developer (with 10 years more experience than I) was reviewing my code before a check-in and had never seen the conditional expression used outside a call expression/parameter list.

Anyways, enough about my life. I think the ?? option should be added... I use that sort of thing in scripting languages all the time, and now that I know the dangers of the ?:, I might even use it more frequently than that. I don't think it should be limited just to object references; as nulls evaluate to false, it could be extended to other types with a logical false such as integers or boolean expressions:

int x = 0 ?? 10; // Evaluates to 10
int y = 5 ?? 10; // Evaluates to 5
int z = 0 ?? 0; // Evaluates to 0
bool a = false ?? true; // Evaluates to true
bool b = false ?? false; // Evaluates to false

 ??? seems very weird to me, though, so I'm against that one.



More information about the Digitalmars-d mailing list