The D Programming Language: cases

paul pedersen pedersen at acf3.NYU.EDU
Fri Mar 4 07:56:59 AEST 1988


In article <25200 at cca.CCA.COM> g-rh at CCA.CCA.COM.UUCP (Richard Harter) writes:
>Well, yes, one ought to be able to do that.  However it is isn't quite
>as strong as fallthrough, where one can say
>
>	switch (e) {
>	  case foo:
>	    some code;
>	    fallthrough;
>	  case baz:
>	    some more code;
>	  }
>
>
>In C as it stands now you can do this -- indeed, the complaint is that
>one can do this unintentionally.  If one adds aggregate constructors and
>takes away automatic fallthrough, it seems to me that you weaken the
>language.   No doubt there are purists that say you shouldn't do the
>sort of thing given above.  I wouldn't go that far, but I would agree
>that one should be able to use aggregate constructors when cases actually
>share code.
>

Fallthrough may be occasionally justifiable.  One good example (stolen
from Knuth's classic article "Structured programming with go to statements")
is a P-code-type interpreter, where the Subtract case may negate one 
operand and then branch to the Add case.  I think that a better D option
would be to mark this explicitly with the classic language for marking
an "abnormal" transfer of control:

	switch (op) {
	case Add:
		blah-blah-blah
	case Subtract:
		negate operand;
		goto case Add;
	/* more cases */
		}

This 'goto' is signalled as exceptional by the reserved word 'case' appearing
in place of a label.  The use of 'goto' rather than 'fallthrough'
is also superior because it is not as fragile if a new case is introduced.

I do not think, however, that such a "general" concept as either fallthrough
or on-the-fly constructors should be  used to support the common
use of multiple cases which execute exactly the same code.
Here some other syntax is needed.  The natural 'case a,b,c:' is defeated
by C's comma operator, and 'case a:b:c:' is not LL(1) parseable, but
some other C-ish syntax can probably be invented.

In current practice, when I need to fall through, I always use the conventional
comment /* FALLTHROUGH */ to mark the spot.



More information about the Comp.lang.c mailing list