generalized switch

aglew at ccvaxa.UUCP aglew at ccvaxa.UUCP
Wed Aug 6 10:16:00 AEST 1986

... > Generalized switch

Agreed, a cascade of ifs is the way to implement a generalized
alternative statement in C:
	if( C1 ) 
	else if( C2 )

However, in a higher level language than C there are many potential
advantages to a generalized switch (I prefer to say alternative)

If the expressions are complicated, eg. (in my preferred syntax
- the ::s would be blocks `a la Dijkstra if I had them)

	IF C1 AND C2 THEN ...
	:: C1 AND NOT C2 AND C3 THEN ...
	ELSE ...

you probably would not want to implement them as a cascade of IFs
- you would probably want to use some sort of tree structure
	if( C1 ) 
		if( C2 ) ...
		else ...
	else if( !C2 && C3 ) ...
	else ...
as the expressions get more complicated so does the tree, obscuring
the original branching at one point nature of the original code.
A compiler that understood a bit about logical expressions could
generate a good tree for you, automatically.

In fact, if you can ascribe probabilities to each of the conditions
or branches, an optimum tree from the point of view of speed can
be easily generated automatically. I apply this Huffman algorithm
myself in my hand coding, when I have to worry about speed.

Also, the generalized alternative is not, strictly speaking, a cascade.
Ie. no two of the alternatives should simultaneously hold, in a 
deterministic language (in an undeterministic language multiple
alternatives may be valid, of which one or more at random may be
taken). In this example
	IF C1 AND C2 THEN ...
	:: C1 AND C3 THEN ...
	ELSE ...
C2 and C3 should not simultaneously hold if C1, for a deterministic 
language. A compiler can easily generate checks for this.

Anyway, enough of that. Returning to the language I have to work in,
I have found a similar construct useful in C. Coming from an 
engineering background, I am used to working in truth tables -
I like laying out functions
	Inputs		Outputs
	TTT		S1
	TFT		S2
	F**		S3
In computational geometry I've gone 5 inputs deep (with lots of
don't care conditions). Laying these out as a tree of IFs obscures
the tabular nature of my understanding of the problem, but this
can be remedied with a few #defines in C:

	switch( boolvec(C1,C2,C3) ) {
		case TTT:	S1; break;
		case TFT:	S2; break;
		case Fxx:	S3; break;

OK, folks, tell me I'm ...

Andy "Krazy" Glew. Gould CSD-Urbana.    USEnet:  ihnp4!uiucdcs!ccvaxa!aglew
1101 E. University, Urbana, IL 61801    ARPAnet: aglew at gswd-vms

More information about the Comp.lang.c mailing list