Path: utzoo!attcan!uunet!lll-winken!lll-tis!ames!ncar!oddjob!mimsy!chris
From: chris@mimsy.UUCP (Chris Torek)
Newsgroups: comp.std.c
Subject: Re: switch (expression)
Message-ID: <12484@mimsy.UUCP>
Date: 14 Jul 88 17:56:21 GMT
References: <1988Jul12.105547.13268@light.uucp> <7329@cup.portal.com>
Organization: U of Maryland, Dept. of Computer Science, Coll. Pk., MD 20742
Lines: 65

In article <7329@cup.portal.com> Paul_L_Schauble@cup.portal.com writes:
>And while we're at it, seems to me as though the expression in
>  switch (Type)
>should allow any Type for which the == operator is defined.

The reason switch works the way it does is that it `wants to'
compile into a computed goto:

	switch (i) {
	case 1: ... break;
	case 2: ... break;
	   .
	   .
	   .
	case 37: ... break;
	default: ... break;
	}

compiles to

	reg = i-1
	(unsigned)(reg - 36)
	>= 0 ? goto default
	goto cases[reg]

A more general version appears in Mesa:

    SELECT expression FROM
    { expression => statements }*
    END

(syntax very approximate).  All `expression's are arbitrary; the
language is defined such that the first `expr =>' that matches the
selected expression takes effect.  It is up to the optimiser to notice
that all the `expr =>'s are constant (if indeed they are) and turn this
into a computed goto; if some of the `expr's are non-constant, the
whole thing must usually be compiled as a series of if/else tests.

The construct does have some advantages.  For instance, instead of

	IF      bool-exp1 THEN stmts1
	ELSE IF bool-exp2 THEN stmts2
	ELSE IF bool-exp3 THEN stmts3
	   .
	   .
	   .
	ELSE		       stmtsn

one can write

	SELECT TRUE FROM
		bool-exp1 => stmts1
		bool-exp2 => stmts2
		bool-exp3 => stmts3
		   .
		   .
		   .
		TRUE =>	     stmtsn
	END

and of course a series of `if not bool-exp' statements can be written
even more simply as `SELECT FALSE FROM bool-exp ...' (although then
the `default' must be written `FALSE => ...').
-- 
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163)
Domain:	chris@mimsy.umd.edu	Path:	uunet!mimsy!chris