Switch-case made less buggy, now with PATCH!

Chad J chadjoan at __spam.is.bad__gmail.com
Sat Nov 21 11:24:02 PST 2009


Don wrote:
> 
> Things like
> 
> case A:
> case B:
>       foo();
>       break;
> 
> do not involve fallthrough bugs. If there's a bug in that code at all,
> it's that case A doesn't do anything. Empty case statements are not
> bug-prone.
> 

My intent is not to forbid these.  I suppose I've tried to damage them
as little as possible.  Letting them slip through without notation would
do better on that count.  It's a trade-off between that and easier
(general) fallthrough syntax.

With this syntax the code required to convert C-style switch-case to
D-style becomes much easier.  You can just look for case and replace :
with !:.  Otherwise you have to figure out where to put the goto case
statement, which is usually easy enough for a human, but can be tricky
for a program that doesn't have a D parser.  Unless you are OK with
generating some garbage:

switch(foo)
{
    case 0:
        switch(bar)
        {
            case 0:
            case 1:
            // but for case 2:
            ...
        }

    case 1:
    ...
}

becomes

switch(foo)
{
    case 0:
        switch(bar)
        {
            goto case 0; case 0: <-- yuck.
            goto case 1; case 1:
            // but for goto case 2; case 2:
            ...
        }

    goto case 1; case 1:
    ...
}

You could always just follow compiler errors though, so it's a minor point.

> The thing is, that with the "goto case" syntax, D already has support
> for explicit fallthrough. No new syntax is required.
> 

I know this.  Walter knows this.  Why hasn't it been given emphatic
thumbs up?

I suspect it's because he's either busy with more important things or
really enjoys fallthrough.

Given how easy it is to remove implicit fallthrough and given that he's
expressed a strong fondness of the fallthrough behavior, I suspect it's
more the latter than the former.

At any rate, I've decided to solve both.  So here's a patch to make it
even easier to enact (especially docs + lib migration), and also a
syntax to keep fallthrough easy and compact where desired.

If the syntax is a bad idea, then it can be ditched, and I'll make a new
patch.  All Walter has to do is say the word.

> BTW accidental fallthrough can be detected in the parse step, no
> semantic analysis is required, which makes it particularly easy to
> implement in a lint tool.

Lint tools
- Don't exist for D. (AFAIK)
- Add another step to my workflow/build process.  The compiler should be
doing this stuff anyways.

So yeah, I don't really care much for lint tools.  Let's just Do It
Right and not need any lint tools.

- Chad



More information about the Digitalmars-d mailing list