Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!ames!pasteur!ucbvax!tut.cis.ohio-state.edu!rutgers!att!ulysses!andante!alice!ark From: ark@alice.UUCP (Andrew Koenig) Newsgroups: comp.lang.c Subject: Re: function casting Message-ID: <9266@alice.UUCP> Date: 30 Apr 89 15:49:23 GMT References: <12481@umn-cs.CS.UMN.EDU> Organization: AT&T Bell Laboratories, Liberty Corner NJ Lines: 57 In article <12481@umn-cs.CS.UMN.EDU>, clark@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@europa.att.com