Path: utzoo!mnetor!uunet!husc6!think!barmar From: barmar@think.COM (Barry Margolin) Newsgroups: comp.lang.c Subject: Re: The D Programming Language: switches Message-ID: <18377@think.UUCP> Date: 22 Mar 88 16:57:25 GMT References: <222965b9@ralf.home> <941@micomvax.UUCP> <3074@haddock.ISC.COM> <25835@cca.CCA.COM> <1186@PT.CS.CMU.EDU> Sender: usenet@think.UUCP Reply-To: barmar@fafnir.think.com.UUCP (Barry Margolin) Organization: Thinking Machines Corporation, Cambridge, MA Lines: 26 In article <1186@PT.CS.CMU.EDU> edw@IUS1.CS.CMU.EDU (Eddie Wyatt) writes: > >>Yes, in a sense switch is less powerful than an else-if chain. Let's keep it, > >>for the same reasons that we retain flow constructs less powerful than goto. > > Theoretically the switch construct is more powerful than an else-if > > chain because it selects in one step. Execution is O(1) rather than O(n) > > where n is the number of branches. It is, for example, considerably more > > efficient to use a switch with a thousand cases than an else-if chain with > > a thousand elses. [This is not to be taken as an endorsement of such > > code. :-)] > 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). Barry Margolin Thinking Machines Corp. barmar@think.com uunet!think!barmar