c types problem
David Tribble
tribble_acn%uta.csnet at csnet-relay.arpa
Wed Jan 8 20:47:40 AEST 1986
In article <870 at kuling.UUCP> gostas at kuling.UUCP writes:
>The formal (but ugly) way to solve this would probably be to use a union
>for all (about 10) types. But now I wonder if anyone has a simpler but
>reasonably portable solution?
The only way that is truly portable that comes to mind is to use a union.
However, the following way works on many (not all) machines and is somewhat
portable (meaning it is not truly portable):
foo (typ, arg)
int typ;
double arg;
{
char* argp;
...
argp = (char*) &arg;
switch (typ) {
case CHR: c = *(char*)argp;
case INT: i = *(int*)argp;
case FLT: f = *(float*)argp;
case DBL: d = *(double*)argp;
... ...
}
}
foo is the routine that is passed the arg or unknown type, and foo
knows what type arg is by the value of typ.
The idea is to pass the parm (declared as a type that will probably be aligned,
thus 'double'), take its address (which is usually on the stack), cast
the address (pointer) to the appropriate pointer type, then de-reference
the casted pointer. This is based on the assumption that parameters of
different types will reside at the same location (ie, their lower bytes
have the same alignment).
Yes, it's hokey, and yes, it will not work on machines that align function
arguments in funny ways.
-----
Another variant to this scheme is to call foo passing it the address of
the object, declaring foo-
foo (typ, argp)
int typ;
char* argp;
This solves the alignment problem. However, since you can only
take the address of an lvalue, you cannot pass foo the address of an
expression. This scheme suffers from nonportability since casting
pointers to different types is wierd on some machines.
Given my choice, I would probably use the pointer-passing scheme, since
it is (mostly) portable and doesn't require macros (only an '&' operator)
or extra unused space for local unions.
[The usual disclaimers go here.]
david r. tribble univ. texas at arlington
tribble_acn at uta
More information about the Comp.lang.c
mailing list