The D Programming Language: switches

Eddie Wyatt edw at IUS1.CS.CMU.EDU
Wed Mar 23 05:52:36 AEST 1988


> >  I think he meant in terms of expressability.  Which is true in a
> >practical sense, false in theorectically.  'switch' and 'else-if'
> >are equivalent in terms of expressability.
> 
> That is obviously untrue.  A switch can only check one expression, and
> can only compare it against constant values.  An else-if chain can
> check for multiple conditions and can compare computed values.  You
> can even have side effects in the conditional expressions, which can
> affect later conditionals (I don't recommend this practice taken to
> extreme, but things like 'if ((ch = getchar()) == EOF) ... else if (ch
> == '\n') ...' aren't too bad).

Outline of the prove that switch could replace an else-if chain.  The
opposite direction is trivial and is left for the ready to prove :-)


Actually one needs to do an induction proof, but this is just an outline.


	if (cond1) 	expr1
	else if (cond2) expr2
	else if (cond3) expr3
	....
	else if (condN) exprN

is equivalently rewritten as:

	if (cond1) expr1
	else 
	    { 
	    if (cond2)	expr2
	    else	
		{
		if (cond3) expr3
		else
		    {
		    .......
		    }
		}
	    }

forever pair of if (cond) expr1 else expr2 rewrite the statement as:

	switch(cond)
	    {
	    case TRUE  :	expr1; break;
	    case FALSE :	expr2; break;
	    }

so the else-if chain becomes:

	switch(cond1)
	    {
	    case TRUE  : 	expr1; break;
	    case FALSE :
		switch (cond2)
		    {
		    case TRUE :		expr2; break;
		    case FALSE :	......
		    }
		break;
	    }


Remember what I said, in a practical sense, yes one needs else-ifs but
in a theorical sense, you gain nothing in terms of the expressable functions.
-- 

Eddie Wyatt 				e-mail: edw at ius1.cs.cmu.edu



More information about the Comp.lang.c mailing list