If Statement with Declaration
Jonathan Marler via Digitalmars-d
digitalmars-d at puremagic.com
Wed Jul 19 08:03:10 PDT 2017
On Wednesday, 19 July 2017 at 13:30:56 UTC, sontung wrote:
> So I was thinking of a way of extending if statements that have
> declarations. The following being as example of the current use
> of if statements with declarations:
>
> if(int* weDontPollute = someFunc())
> {
> // use weDontPollute
> }
>
> That's great and all, but it only works by checking if the
> variable evaluates to true or false. Which is fine for a
> pointer but otherwise useless for anything else, like integers
> where zero is usually valid input (index for array). So
> currently the only way to do something like this in the
> language, that i've found, is to use a for statement.
>
> for(int i = someFunc(); i >= 0;)
> {
> // use i
>
> break;
> }
>
> Not that ideal to use a for statement. It makes it hard to read
> and if the break condition isn't there it might very well be an
> infinite loop. So I was thinking of some sort of syntax like
> this:
>
> if(int i = someFunc(); i >= 0)
> {
> // use i
> }
> Thoughts on this sort of feature?
Achieving the same semantics as your example today would look
like this
{
int i = someFunc();
if(i >= 0)
{
// use i
}
}
The disadvantage being that it creates an extra level of nesting.
I can see how this extra scope can discourage people from
properly scoping their variables and this feature would eliminate
the need for the extra scope.
Also note that this example shows how this could be implemented
using "syntax lowering".
if( <declaration1> ; <desclaration2> ; ... ; <condition)
{
//
}
Becomes:
{
<declaration1>;
<declaration2>;
...
if(<condition>)
{
// ...
}
}
More information about the Digitalmars-d
mailing list