Variable assignment in “if” condition in Dlang

kdevel kdevel at vogtner.de
Sun May 3 16:30:26 UTC 2020


On Sunday, 3 May 2020 at 15:13:48 UTC, H. S. Teoh wrote:
> On Sun, May 03, 2020 at 02:53:21PM +0000, Baby Beaker via 
> Digitalmars-d-learn wrote:
>> How can I assign a variable in “if” condition in Dlang?
>
> 	if (auto obj = someFunction(...)) {
> 		// use obj here, it's guaranteed to be
> 		// true/non-null/etc.
> 	}

What if someFunction's return type is string? I mean this:

```if.d
void eval (string function () fun)
{
    import std.stdio;
    if (auto s = fun ())
       "true".writeln;
    else
       "false".writeln;
}

void main ()
{
    () { string s; return s; }.eval;       // empty string
    () { string s = ""; return s; }.eval;  // empty string
}
```

It surprisingly [1] [2] prints:

    false
    true

In the string case there is at least not the guarantee that the 
string is non-empty.

[1] Empty string vs null
     
https://forum.dlang.org/thread/fehvcobsjuklxynbqqox@forum.dlang.org

[2] The Nullity Of strings and Its Meaning
     
https://forum.dlang.org/thread/qcmtjfpkvcoyvrouvccw@forum.dlang.org


More information about the Digitalmars-d-learn mailing list