Must the "switch" quantity be an integer?

Doug Gwyn gwyn at smoke.BRL.MIL
Thu Oct 20 09:18:03 AEST 1988


In article <6137 at june.cs.washington.edu> pardo at cs.washington.edu (David Keppel) writes:
>    #define	BUFPTR		((os_t *)1)

This is quite non-portable.  ANSI C requires that there be some integral
type to which a pointer can be cast then uncast without loss of information,
but the integral type isn't necessarily int, and random integer values need
not be castable to pointers.

If you really have to have os_t*-shaped magic numbers, consider using real
data objects for them:
	static os_t dummy_buf;
	#define BUFPTR (&dummy_buf)

>(a) What are the rules?

The switch expression must be an integral expression.

>(b) Can I do this portably without using a mass of
>    if (foo[i]==BUFPTR) { ... } else if (foo[i]==SPTR)...
>    code?  (Or, "*can* I do this portably?")

One way, assuming that you use actual objects as I suggested above
and that ptrint_t is the integral type defined for pointer-to-integer
mapping for your implementation (the typedef needs to be adjusted
when porting):

	switch ( (ptrint_t)foo[i] )
		{
	case (ptrint_t)BUFPTR:



More information about the Comp.lang.c mailing list