Article View: comp.std.c
Article #5182switch (expression)
From: Bakul Shah
Date: Tue, 12 Jul 1988 17:55
Date: Tue, 12 Jul 1988 17:55
61 lines
2405 bytes
2405 bytes
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>
Technical Details
Message-ID:
<1988Jul12.105547.13268@light.uucp>Path:
arc1-ca.pugleaf.net!utzoo!attcan!uunet!husc6!bloom-beacon!mit-eddie!ll-xn!ames!amdcad!light!bvsShow Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!utzoo!attcan!uunet!husc6!bloom-beacon!mit-eddie!ll-xn!ames!amdcad!light!bvs From: bvs@light.uucp (Bakul Shah) Newsgroups: comp.std.c Subject: switch (expression) Message-ID: <1988Jul12.105547.13268@light.uucp> Date: 12 Jul 88 17:55:45 GMT Reply-To: bvs@light.UUCP (Bakul Shah) Lines: 61