Declaration in expression - Re: Python-like Use of the Comma Expression

Basile B. b2.temp at gmx.com
Fri Aug 11 18:40:26 UTC 2023


On Friday, 11 August 2023 at 12:16:49 UTC, Nick Treleaven wrote:
> On Thursday, 10 August 2023 at 21:38:25 UTC, Basile B. wrote:
>> whe have var decl syntax for `if`, since recently for `while` 
>> too... It's pretty clear that "in situ" variable decls are 
>> required...unless D continues on making special cases.
>
> For `if (auto x = expr)`, the scope of `x` includes the 
> *ThenStatement*.
> For `if ((auto x = expr) || b)`, `x` can have similar scope.
> For `if (b && (auto x = expr))`, `x` can have similar scope.
> I think the above two cases could be supported in D.

Probably but trust me, allowing the declaration as an expression 
really solves the problem in a clean way.

> For `if (b || (auto x = expr))`, `x` may be uninitialized if it 
> is accessible in the *ThenStatement*. Does Styx forbid that and 
> similar cases?

No, such cases are allowed because locals are default 
initialialized before the `if`. It is then up to the programmer 
to test again if `x` is set to a particular value but at least is 
guaranteed not to be undefined.

Otherwise the only restriction (checked during a semantic pass) 
is that the declaration needs to be between parens if used as 
AndAnd or OrOr operand, as otherwise the operand can become part 
of the LHS initializer.

```
if var a = getA() && var b = getB() do {} // parse but sema error
if (var a = getA()) && (var b = getB()) do {} // ok
```

And in case the intention was really to have a single expression 
as condition.

```
if var a = (getA() && (var b = getB()) do {}
```

> Also for `if (b || ((auto x = expr) && x.b))`, `x` is safely 
> used but it may be uninitialized if its scope extends to the 
> *ThenStatement*.

Yes but this is considered as a programming error.


More information about the Digitalmars-d mailing list