Path: utzoo!mnetor!uunet!husc6!bbn!rochester!PT.CS.CMU.EDU!IUS1.CS.CMU.EDU!edw From: edw@IUS1.CS.CMU.EDU (Eddie Wyatt) Newsgroups: comp.lang.c Subject: Re: The D Programming Language: switches Message-ID: <1196@PT.CS.CMU.EDU> Date: 22 Mar 88 19:52:36 GMT References: <222965b9@ralf.home> <941@micomvax.UUCP> <3074@haddock.ISC.COM> <18377@think.UUCP> Sender: netnews@PT.CS.CMU.EDU Organization: Carnegie-Mellon University, CS/RI Lines: 69 > > 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@ius1.cs.cmu.edu