Felix Kater <fk****@googlemail.comwrites:
AFAIK there is no way in C to define one single function argument so
that two ore more explicitly declared types are allowed to pass
(so, either you pass the exact type or you need casts which I explicitly
do *not* want to consider here).
With the touch of a C enhancement in mind, I wonder, though, why
this shouldn't be allowed (it is *not* at least by my C compiler
gcc):
union u{
int i;
long l;
char* pc;
};
void f(u arg){
"u arg" needs to be "union u arg".
/* ... */
}
void main(int argc,char** argv){
main returns int, not void.
i=99;
int i = 99; (as you mentioned in a followup)
f(i); /* <-- INCOMPATIBLE TYPE */
}
Yes, of course, i is an int while union u is needed. On the other hand:
Wouldn't type checking be possible since all allowed types are defined
by the union u?
This isn't allowed because the argument i is of type int, and the
parameter arg is of type union u. They're two distinct types, and
there's no implicit conversion between them. A "union u" isn't an
int, it merely contains an int.
Now it would have been easy enough for the language to support this,
by defining an implicit conversion between a union type and any of its
member types.
But the language already has plenty of mechanisms for doing this kind
of thing. Unions are tricky enough as it is; accessing any member
other than the one most recently stored invokes undefined behavior
(though I think there are exceptions for things like character types,
and for types whose representation is guaranteed to be the same).
The function needs to know *which* member of the union is current. A
good way to do that is to wrap the union in a structure, which has
another member that tells you which union member is active:
struct variant {
enum { i_is_active, l_is_active, pc_is_active } discriminant;
union {
int i;
long l;
char *pc;
} u;
};
Constructing a value of this type is a little tricky, especially in
C90.
Or you can use a variadic function, using the <stdarg.hheader, with
a single fixed argument specifying the type of the second argument.
This is how printf() works.
There are almost infinitely many features that C *could* support, and
almost every one of them could be useful in some context. But if they
were all added, the standard document would collapse into a
gravitational singularity. The obvious solution is to add just the
features that *I* think would be useful, but nobody else would like
the result.
--
Keith Thompson (The_Other_Keith)
ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"