Improvements to switch
Basile B.
b2.temp at gmx.com
Tue Apr 30 13:15:45 UTC 2024
On Saturday, 27 April 2024 at 14:58:19 UTC, IchorDev wrote:
> On Tuesday, 16 April 2024 at 16:00:48 UTC, Basile B. wrote:
>> About this, the main point is rather
>>
>> ```d
>> /*-->*/ const /*<--*/ int myvalue = switch(code) {
>> // ...
>> };
>> ```
>>
>> "ah finally you can define a const var decl that relies on
>> branching" (without using the conditional expression...)
>
> You can already do that.
> ```d
> const string myValue = (){
> switch(code){
> case 1: return "what";
> case 2, 3: return "ok";
> default: return "no";
> }
> }();
Besides the problems exposed in the first answer (essentially:
"it's a workaround") I've found a case where this does not work.
It's about selecting an lvalue with a switch:
```d
void main()
{
int a,b,c,d,cond;
auto ref () {
switch (cond)
{
case 1: return a;
case 2: return b;
case 3: return c;
default: return d;
}
}() = 0;
}
```
see https://issues.dlang.org/show_bug.cgi?id=24525
The switchexp would have the same problem: the parser sees
"switch" then it branches on statement parsing. Statement parsing
sees "switch", then it branches on SwitchStmt parsing.
Not so dramatic but the lambda solution is 1. a workaround, 2.
not perfect.
For that case you have 1. to explain the lambda trick 2. why you
have to put the lambda between parens.
With the switch expr, you just have to explain point 2.
More information about the dip.ideas
mailing list