Path: utzoo!mnetor!uunet!husc6!cca!g-rh From: g-rh@cca.CCA.COM (Richard Harter) Newsgroups: comp.lang.c Subject: Re: The D Programming Language: switches Message-ID: <25886@cca.CCA.COM> Date: 23 Mar 88 00:23:12 GMT References: <222965b9@ralf.home> <941@micomvax.UUCP> <3074@haddock.ISC.COM> <25835@cca.CCA.COM> <1186@PT.CS.CMU.EDU> <18377@think.UUCP> Reply-To: g-rh@CCA.CCA.COM.UUCP (Richard Harter) Organization: Computer Corp. of America, Cambridge, MA Lines: 51 In article <18377@think.UUCP> barmar@fafnir.think.com.UUCP (Barry Margolin) writes: >> > 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). We're talking apples, oranges, and pears, here. The switch construct is superior to the else-if chain in computational efficiency, in the sense that it can select between n alternatives in one step rather than n steps, when the selection is made on the value of a variable which has a range of length n. An else-if chain can be replaced by successive switches or by a single switch contained within a while loop (in C with no additional if's), e.g. more = 1; kludge = 0; while (more) switch(kludge) { case 0: kludge += (1 + (expr1)); break; case 1: kludge = 3; break; case 2: action1; more = false; break; case 3: kludge += (1 + (expr2)); .... [This code does not have the good programming stamp of approval.] If we ignore questions of computational power and simply consider expressive- ness, else-if chains can obviously replace switches. And, of course, if we program reasonably, we use each where it is appropriate. (Easier said then done.) -- In the fields of Hell where the grass grows high Are the graves of dreams allowed to die. Richard Harter, SMDS Inc.