Solution of array of pointers to functions problem

Chris Torek chris at mimsy.UUCP
Mon Jun 19 17:04:43 AEST 1989


In article <11964 at pur-ee.UUCP> hankd at pur-ee.UUCP (Hank Dietz) writes:
>... unlike old C, ANSI C is supposed to make things be the type you
>specify in the prototype...  but function pointers wouldn't have
>prototypes (or would they?).

They would.

>For example, suppose that p is a pointer to either a function f which
>returns an int and takes a short arg or to function g which returns an int
>and takes a long arg...

This type does not exist in pANS C.  p may be declared as one or the
other, but not both.  Either value may be stored in p, provided p is
properly cast before the call.

>what is the type, short or long, when the value 5
>is passed in code like (*p)(5)?

If p is written as

	int (*p)(short);
	int f(short);

	p = f;
	(*p)(5);

the argument `5' is converted to a `short' on the way to f().  If
we then add

	int g(long);

and try

	p = g;

we should get a compile-time error.  Changing this to

	p = (int (*)(short))g;

should make it compile; however, the call

	(*p)(5);

will then attempt to pass a short 5 to a routine expecting a long;
what happens is not predictable.  Perhaps the workstation catches
fire.%  To make it predictable (and, incidentally, work), we can
instead use

	(*(int (*)(long))p)(5);

which will convert the 5 to a long on the way to g().

Note that a declaration like

	int (*p)();

is, like

	int f();

deprecated.
-----
% This does seem rather unlikely.  Still, defensive programming suggests
  that one keep a bucket of water handy. :-)
-- 
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163)
Domain:	chris at mimsy.umd.edu	Path:	uunet!mimsy!chris



More information about the Comp.lang.c mailing list