The new ?? and ??? operators

Nathan Reed nathaniel.reed at gmail.com
Sun Sep 23 16:48:40 PDT 2007


Robert Fraser wrote:
> 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.

Is there any reason that || couldn't be overloaded to do this?  It does 
exactly the same thing except that the result is always a bool.

a || b || c || ...

The expressions are evaluated one by one starting from the left, and the 
first one that is true when implicitly converted to a bool is returned. 
  If b is 'true' (meaning, it's a non-null reference, a non-zero number, 
etc), then c is never evaluated.  If all the expressions are 'false' 
(null reference, 0, etc) then the last one is returned.

Similiarly, we could define && such that

a && b && c && ...

results in the expressions being evaluated one by one starting from the 
left, and the first one that is 'false' is returned, or if they are all 
'true', the last one is returned.  If b is 'false', then c is never 
evaluated.

This seems like it could be useful, wouldn't break existing code (as the 
results of these expressions would still be implicitly converted to bool 
when necessary), and don't introduce new operators into the language.

Thanks,
Nathan Reed



More information about the Digitalmars-d mailing list