static if enhancement

Jonathan M Davis via Digitalmars-d digitalmars-d at puremagic.com
Sun Jun 26 17:31:39 PDT 2016


On Friday, June 24, 2016 13:54:21 Andrei Alexandrescu via Digitalmars-d wrote:
> On 6/24/16 1:15 PM, Steven Schveighoffer wrote:
> > The problem that hasn't been made clear is, why can't you just write:
> >
> > static if(condition)
> > {
> >
> >     ... // some code
> >     return;
> >
> > }
> >
> > // some more code
> >
> > And the answer is, I'm guessing, bug 14835 -- misguided "unreachable
> > statement" warnings.
> >
> > Should we mark your bug as a duplicate?
>
> Sorry, the problem is that the code doesn't compile at all if the static
> if is false. So I need to insert the "else".
>
> The compiler should not attempt at all to compile the code after the
> static if.

I would think that it's highly unintuitive to think that code outside of a
static if would be treated as part of an else of a static if just because
the static if happens to return at the end. Certainly, if the code after the
static if couldn't compile if the static if code didn't return, I definitely
think that the code following it needs to be in an else. Really, it seems to
me that this comes down to a complaint about the compiler producing errors
on unreachable code - which is the sort of thing that I tend to think should
not be treated as an error - _especially_ with how badly it tends to
interact with generic code.

So, as long as the code following the static if is valid without being in an
else for the static if, I'm all for having the compiler just optimize out
everything after the return without complaining - but if we're going to do
that, it really shouldn't be specific to static ifs. That would be
unreasonably inconsistent IMHO. And I don't think that it's a good idea to
treat code following a static if as if it were in an else just because of a
return statement or break statement or some other control statement in the
static if which would cause the code after it to be skipped. That would be
confusing and inconsistent IMHO, much as it would be nice to avoid the extra
braces and indentation.

So, if we're going to change things here, I think that the approach is to
stop having the compiler complain about unreachable code, which I think is
very reasonable in light of how annoying that can get - particularly with
generic code - though I'm sure that some folks will be unhappy about that
just like some folks want the compiler to complain about unused variables
(though we don't do that in part because of how badly it interacts with
various D features - like highly templatized code - and that's pretty much
the main reason that having the compiler complain about unreachable code is
so problematic, which could be an argument to have it stop complaining about
it).

- Jonathan M Davis



More information about the Digitalmars-d mailing list