function casting

Andrew Koenig ark at alice.UUCP
Mon May 1 01:49:23 AEST 1989


In article <12481 at umn-cs.CS.UMN.EDU>, clark at umn-cs.CS.UMN.EDU (Robert P. Clark) writes:

> How do I cast something to a pointer to a function that returns
> an integer? One of my (failed) attempts has been


> main()
> {
>   int  (*f)();
>   char *foo();


>     f = ((*int)())foo();  /*  foo returns char*, but I know this is  */

> }

Best would be to make foo return an appropriate pointer ane
avoid type cheating:

	int (*foo())();
	int (*f)();

	f = foo();

The declaration of foo here says that if you call foo, dereference the
result, and call that, you get an int.  The definition of foo would
look something like this:

	int (*foo())()
	{
		/* ... */
	}

Don't be too astonished if your compiler balks at this -- but
it is indeed valid C.

Next question: how to declare a variable to contain a pointer to
a function that returns an integer?  If f is such a variable,
then to get an integer from it, you dereference it (to get a
function from the function pointer) and then call the function.
As your example shows, such a declaration looks like this:

	int (*f)();

Finally, how do you cast a value to the type of f, assuming
you still want to?  A cast looks a lot like the declaration
with parentheses around it, and with the variable removed
that was declared.  So int(*f)() becomes (int(*)()) and the
assignment looks something like this:

	f = (int(*)()) foo();

Of course, the cast is unnecessary if you get the type of
foo right to begin with.  [C-T&P, p. 13]
-- 
				--Andrew Koenig
				  ark at europa.att.com



More information about the Comp.lang.c mailing list