If Statement with Declaration

Jonathan M Davis via Digitalmars-d digitalmars-d at puremagic.com
Sat Nov 5 12:52:05 PDT 2016


On Thursday, November 03, 2016 22:29:34 Jerry via Digitalmars-d wrote:
>      if(int i = someFunc(); i >= 0)
>      {
>          // use i
>      }
> Thoughts on this sort of feature?

Personally, I'd love to have it, and I think that it's been suggested before
(though I don't remember how that discussion went). I think that it would be
a nice syntactic improvement over what Stefan suggested with an additional
set of braces. It also would work with the else if case, whereas adding an
extra scope would not. And I think that any chance of it actually being
added to the language would hinge on its ability to either make stuff
possible which is not currently possible or on its ability to make stuff
that's really awkward easy to do in a non-awkward way. And there's a better
case to be made that

if(cond)
{
}
else if(auto result = foo(); cond2)
{
}
else if(cond3)
{
}

is harder to emulate with the current language than doing it with the first
if - though even with the first if branch, if you have something like

if(auto result = foo(); cond1)
{
}
else if(cond2)
{
}
else if(cond3)
{
}

the variable created in the first if branch would presumably leave scope
immediately after the condition failed, which would also be much more
difficult to emulate by adding additional braces.

So, maybe it could be argued successfully with a DIP, but in general at this
point, I think that Walter and Andrei are very resistant to making changes
to the language - especially when it's simply for aesthetic benefit. So,
any proposing a feature needs to be able to show that it brings real value.
And while I, personally, think that this brings real value for certain use
cases, I don't know if it brings enough value in general to be worth the
addition, and more importantly, I don't know if Walter or Andrei would think
that it's worth it, and they're the ones who need to be convinced.

Ultimately though, the biggest hurdle is that someone needs to create a DIP
for it that strongly argues its case with real world examples of how it
would improve code (preferably with code from Phobos and code.dlang.org),
and without a really well-written DIP it's going to be dead in the water
unless Walter or Andrei already happened to have wished for something like
that often enough that they didn't take much convincing (which I wouldn't
bet on). Right now, the bar to get a new feature in is pretty high even
simply from the standpoint of the amount of work required to successfully
propose it.

- Jonathan M Davis



More information about the Digitalmars-d mailing list