switch (expression)

Bakul Shah bvs at light.uucp
Wed Jul 13 03:55:45 AEST 1988


dpANS says the expression in ``_s_w_i_t_c_h (expression)''
must be an integer valued expression.  Any chance of
getting this changed ``must be an integer or ptr valued
expression''?  The current restriction forces one to use
the messier and longer sequence of ``if..then..else if
...'' for pointers.  That is, instead of

	switch (ptr)
	{
	case PTR1:
		foo; bar1; break;
	case PTR2: case PTR3:
		foo; bar2; break;
	default:
		foo; barx; break;
	}

the following must be used:

	if (ptr == PTR1) {
		foo; bar1;
	} else if (ptr == PTR2 || ptr == PTR3) {
		foo; bar2;
	} else {
		foo; barx;
	}

The latter can get quite unwieldy when a ptr has to be
compared with a lot of constants and each case is non-
simple.  Worse, if you wanted to fallthrough one case to
another after doing some work, you'd have to use a
spaghetti of gotos -- hopefully, no one does this.

Note that the switch stmt can be used by casting the ptr
to a long or an int, but I don't know if this is safe on
all architectures -- (casts) should be avoided where
possible.

The change in specification should be to state that a
_s_w_i_t_c_h expression must be either an int or a ptr, and
the _c_a_s_e const expression must be compatible with it.

Except for the stupid default fallthrough, a switch stmt
can be thought of as equivalent to a sequence of
``if..then..else if ... '', where each if-expr is an
equality comparison and anything that can be compared
for equality should be allowed as a switch expressio.

I noticed this when a dpANS compiler we use recently
tightened its type system.  As a resule some switch code
to deal with SIG_DFL, SIG_IGN etc. wouldn't compile
anymore (and I hate to change other people's sensible
and clear code).

Could it be that even though K&R1 forbade mixing ints
with ptrs and specified that only integer expression be
used in a switch expression, all old compilers continued
to treat the switch expression `sensibly' AND _somehow_
the committee overlooked this?

-- Bakul Shah <..!{ucbvax,sun,uunet}!amdcad!light!bvs>



More information about the Comp.std.c mailing list