generalized switch

Mark Nagel u557676751ea at ucdavis.UUCP
Wed Aug 6 01:43:16 AEST 1986


In article <15093 at ucbvax.BERKELEY.EDU> Joshua Kosman writes:
> As I understand it, a switch/case setup compiles exactly the same as
> 	if (var == const1) {.....};
> 	else if (var == const2) {.....};
> 	else  {default_action};
> anyway. (Or am i wrong?). In any case, it can be rewritten that way.

This may be correct on some machines, however, I was under the impression that
the switch'ed variable is only accessed once and the code address is computed
from a vector table created during the compilation.  It thus cuts down on
a lot of comparisons.  This may mean nothing in a one shot switch, but it sure
will be more efficient in a loop.

> But the switch promotes comprehensibility. The situation I
> find (mildly) frustrating is when I have a choice among cases, a
> setup which is conceptually akin to a switch, but is not
> syntactically equivalent because I want to use a slightly different test
> than simple equality.

If you need to test for greater-than or less-than or the like, why not use
an expression in the switch statement that produces the sign of the
difference between the two things you are testing?  If there are more than
two things, use imbedded switches or go ahead and use if-then-else.

> 
> 
> Joshua Kosman		||  "When I was young people used to tell me,
> kos at ernie.berkeley.EDU	||	'When you're 50 you'll understand.' Well,
> Dept. of Music		||	now I'm 50. I don't understand a thing."
> UC Berkeley		||		-- Erik Satie



- Mark Nagel

ucdavis!u557676751ea at ucbvax.berkeley.edu               (ARPA)
...!{dual|lll-crg|ucbvax}!ucdavis!deneb!u557676751ea   (UUCP)


"Ever since I gave up hope, I've felt much better!"
				- a bumper sticker somewhere



More information about the Comp.lang.c mailing list