If Statement with Declaration

Cym13 via Digitalmars-d digitalmars-d at puremagic.com
Wed Jul 19 08:53:21 PDT 2017


On Wednesday, 19 July 2017 at 15:39:02 UTC, Steven Schveighoffer 
wrote:
> On 7/19/17 9:30 AM, sontung wrote:
>> [...]
>
>
> I really like the idea. Only thing I don't like is the 
> possibility for abuse/confusion/errors:
>
> if(int i = someFunc(); j >= 0) // typo, or weird relationship, 
> or just intentional obfuscation?
>
> It reminds me a bit of why we got rid of the comma operator.
>
> This is why I've liked suggestions in the past like:
>
> if((int i = foo()) >= 0)
>
> That is, you want to use 'if' on an expression while saving the 
> expression, but the if is only looking at a property of that 
> expression.
>
> Note this makes if(arr) (the correct meaning, that is ;) much 
> more palatable:
>
> if((auto x = getArray()).length)
>
> Don't get me wrong, if this syntax is what gets this idea in, 
> I'm fine with it.
>
> One possibility is to require usage of the declared variable in 
> the condition.
>
> -Steve

Now that I think about an extension of the comma makes more sense:

     if (int i=foo(), i<42) ...

It is exactly the idea that we are trying to convey here (except 
that, deprecated comma aside, it doesn't work because of scope 
issues: i in i<42 is considered undefined).

Given that the comma will never die and that it conveys exactly 
the idea I think think it should be prefered to the semi-colon.


More information about the Digitalmars-d mailing list