optional assignment

Basile B. b2.temp at gmx.com
Wed Feb 5 15:34:29 UTC 2025


On Sunday, 2 February 2025 at 03:30:17 UTC, Walter Bright wrote:
> ```
> if (!a) a = b;
> ```
>
> Doesn't seem that bad. I did some searches and found hardly any 
> instances of it, though that was across the dmd sources.

I dont't know what regex have you used but here I've just tried 
`if( )+\(\![a-zA-Z_][a-zA-Z_0-9.]*\` and almost directly found an 
interesting example in typesem.d:

```d
Type referenceTo(Type type)
{
     if (type.ty == Terror)
         return type;
     if (!type.rto)
     {
         Type t = new TypeReference(type);
         type.rto = t.merge();
     }
     return type.rto;
}
```

could become

```d
Type referenceTo(Type type)
{
     if (type.ty == Terror)
         return type;
     return type.rto ?= new TypeReference(type).merge();
}
```

in particular here the opt-assign saves the double load on `type` 
to obtain `type.rto` as a lvalue.

More generally to the criticism that is "that does not seem very 
useful" I'd reply that at some point new language additions are 
necessarily "niches".


More information about the dip.ideas mailing list