Variable declaration primary expression
IchorDev
zxinsworld at gmail.com
Mon Jan 20 23:22:38 UTC 2025
On Monday, 20 January 2025 at 21:31:18 UTC, Paul Backus wrote:
> On Monday, 20 January 2025 at 20:41:42 UTC, IchorDev wrote:
>> Someone brought up this clever idea here:
>> https://github.com/dlang/dmd/pull/20653#issuecomment-2581474608
>> What does everyone think about being able to declare variables
>> in expressions? Is there any pre-existing syntax that blocks
>> us from being able to easily do this?
>
> This sounds like a great feature for writing absolutely
> horrendous code.
>
> Imagine: variables declared in the middle of function calls.
> Variables declared inside the initialization of other variables.
>
> struct Point
> {
> double x = (double y = 0);
> }
>
> void main()
> {
> import std.stdio;
> readf("%f, %f", (Point p).tupleof);
> writefln("p = (%f, %f)", p.x, p.y);
> }
>
> Is this really what we want? If someone submitted code like
> this to one of your projects, would you accept it?
This is just stupid. Read the link I posted. You intentionally
using the concept in the dumbest possible way is a completely
worthless argument that could be used against almost every aspect
of D. Here you go:
```d
void
main
(
string
[]
args
)
{
}
```
Would you accept this into your projects? No? What if you got a
PR with variable names in Hindi? No? What if you got a PR that
dereferences uninitialised pointers? No? See it’s not the
compiler’s job to force everyone write code in one specific
‘correct’ way. You can misuse every feature of the language.
That’s your choice, but you can’t blame others saying ‘you can
write stupid code, so the language is faulty’.
Currently, variable declarations in expressions are limited to a
few special cases that make them feel really backhanded and
arbitrarily strict to use.
Want to declare a variable and also run some code if it’s not
null? Easy.
```d
if(auto a = b in c){
//code
}
```
This pattern is great for simplifying null pointer checks. I use
it everywhere. But… what if we want to do it three times, nested?
We can just use `&&` right???
Haha, no. You were tricked and now this nice syntax has gone
rotten. You have to use the pyramid of doom:
```d
if(auto a = b in c){
if(auto d = e in a){
if(auto f = g in d){
//code
}
}
}
```
And suddenly what was a really useful feature becomes a terrible
drag because you can only use it once per if statement, requiring
many layers of nested if statements instead of just utilising the
usual `&&` early-out rules.
More information about the dip.ideas
mailing list