Pointer-to-function casting

topic posted Wed, March 31, 2004 - 8:29 AM by  Bartosz
Share/Save/Bookmark
Advertisement
Do you thing the following is correct C++?

int foo (char * str); // an arbitrary function
void * p = foo; // store PTF as void *

There is an interesting discussion about this at www.relisoft.com/forum/toast.asp .
posted by:
Bartosz
Seattle
Advertisement
Advertisement
  • Re: Pointer-to-function casting

    Sat, April 24, 2004 - 12:56 AM
    I run across void * alot in external libraries that let me attach a reference to a created structure (this is usually C). Motif is an example. Usually the void * ptr was for the user to keep track of whatever he darn well wanted to. The library designers didn't care.

    With that kind of catch all, I see no reason why void * could not point to a code address. Will your compiler take it if you hard cast it (instead of using the C++ casting template?)
    • Re: Pointer-to-function casting

      Sun, May 2, 2004 - 1:10 PM
      My compiler (VS.NET) doesn't care. But it might change in the future releases. It's beter to start being careful about converting pointers to functions. In most cases it's as simple as using void(*)() instead of void* when an arbitrary function pointer may be used.
      And no, the strict reading of the standard doesn't allow any casting between void* and function pointer, even C-style casting.
  • Re: Pointer-to-function casting

    Sun, May 9, 2004 - 12:19 AM
    As far as I know, casting a function pointer to a pointer has always yielded implementation-defined behavior. There are many platforms on which sizeof(function pointer) > sizeof(void*) and on those platforms this code will crash when you try to cast back from void* and call through the function pointer.