canonical values - an amenity

Karl Heuer karl at haddock.UUCP
Fri Dec 5 10:18:57 AEST 1986


In article <1542 at batcomputer.tn.cornell.edu> garry%cadif-oak at cu-arpa.cs.cornell.edu.arpa writes:
>I use [void *] heavily to pass pointers (to structures) through utility
>routines which do not know what type of pointer is coming down, and back
>again to action routines which *do* know what type is coming.
>
>What I would like is to be able to do the same thing with *any* kind of
>(primitive) value, not merely pointer values!!!

There are a few routines, e.g. memcpy(), which can behave reasonably on any
pointer type (cast into "void *").  I find it hard to imagine a routine that
would operate portably on both "double" and "char *" without knowing which.

>... So I need it as a primitive. Ideally it would just be a 64-bit bitmask
>internally rather than a double, to avoid unnecessary conversions.

>From this I assume that you want "(double)unk" and "(int)unk" to just read
the bits directly and not convert -- in other words, the operation performed
by a union rather than a cast.

>A fringe benefit is that I can declare *actual variables* to be of
>type "unknown", and so avoid having to play with unions of {int, char,
>float, double, void *}. 

You can declare actual variables of type union { int, ... }.

Let me make a counterproposal (one which is more likely to be accepted by
the C community):
    typedef union { int asint; char *asstring; double asreal; } universe;
    universe u;  int i;
    ...
    u = (universe)i;
This cast (currently illegal) would be equivalent to "u.asint = i", but is
more powerful since it can be used in contexts other than assignment.  For
example, I could now initialize an array of unions at compile time:
    universe a[] = { (universe)12, (universe)"hello", (universe)5.6 };

The reverse cast "(int)u" could be allowed for completeness, but wouldn't
be as useful since "u.asint" provides the same functionality.

Karl W. Z. Heuer (ima!haddock!karl or karl at haddock.isc.com), The Walking Lint



More information about the Comp.lang.c mailing list