www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Variable assignment in =?UTF-8?B?4oCcaWbigJ0=?= condition in Dlang

reply Baby Beaker <thegrapevine email.com> writes:
How can I assign a variable in “if” condition in Dlang?
May 03 2020
next sibling parent reply "H. S. Teoh" <hsteoh quickfur.ath.cx> writes:
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. } T -- EMACS = Extremely Massive And Cumbersome System
May 03 2020
parent reply kdevel <kdevel vogtner.de> writes:
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
May 03 2020
parent Steven Schveighoffer <schveiguy gmail.com> writes:
On 5/3/20 12:30 PM, kdevel wrote:
 It surprisingly [1] [2] prints:
 
     false
     true
 
 In the string case there is at least not the guarantee that the string 
 is non-empty.
Then you have to do it in 2 steps. It would be nice to have a way to do this, but there isn't right now. -Steve
May 03 2020
prev sibling parent reply Adam D. Ruppe <destructionator gmail.com> writes:
On Sunday, 3 May 2020 at 14:53:21 UTC, Baby Beaker wrote:
 How can I assign a variable in “if” condition in Dlang?
depends on exactly what there's also if ( (a = 10) ) with extra parens for special purposes
May 03 2020
parent Steven Schveighoffer <schveiguy gmail.com> writes:
On 5/3/20 11:27 AM, Adam D. Ruppe wrote:
 On Sunday, 3 May 2020 at 14:53:21 UTC, Baby Beaker wrote:
 How can I assign a variable in “if” condition in Dlang?
depends on exactly what there's also if ( (a = 10) ) with extra parens for special purposes
That doesn't work. You need to do a comparison or a cast. -Steve
May 03 2020