switch (expression)

Paul Gluckauf Haahr haahr at phoenix.Princeton.EDU
Thu Jul 14 01:33:31 AEST 1988


in article <1988Jul12.105547.13268 at light.uucp>,
	bvs at light.UUCP (Bakul Shah) writes:
> 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 problem with pointer valued constants is that they are generally
not constant until link time.  at compile time, most pointer constants
are of the form ``&extern_identifier[constant_expression]'' or some
such, which are relocatable symbols.  therefore, the compiler would not
know about the value of a case expression.  one could in theory have
the compiler generate the cascading if...else if...else... chain from
the switch code, but there would be no way for the compiler to recognize
duplicate pointer values in the switch table until link time.

the only other form of portable constant pointer expression is the
null pointer, which the compiler will know the value of (0).  so,
portably, i believe that
	switch (pointer-expression) {
	case 0:		... ; break;
	default:	... ; break;
	}
but that's just an if statement.

unix uses, in the signal code, ``(int (*)()) small-integer constant'',
but that's not really all that clean.  (is this well-defined and unique
in all ansi compilers?  i'm not sure that it is for all architectures.)
to handle this sort of code in a switch statement, cast everything to
int (or, more accurately, a wide enough integral type).  this is one of
very few standard cases i can think of with more than one compile time
integer constant.

one could of course do the hard work of generating the switch table
at link time rather than at compile time, but that would be a lot of
work, and require compiler-writers to write linkers also.  one more
argument to start doing code generation at link time.

paul haahr
princeton!haahr or haahr at princeton.edu



More information about the Comp.std.c mailing list