Void function pointers

Steven Preston preston at LL.MIT.EDU
Sat Jan 26 06:53:37 AEST 1991


In message <2887 at casbah.acns.nwu.edu> hpa at casbah.acns.nwu.edu (Peter Anvin) writes:
+ Could someone please tell me if this is illegal in ANSI C:

+ void foo(int p1, double p2, void (*zoom)(int x, double y))
[definition of foo]
+ int bar(int baz, double quux)
[definition of bar]
...
+    foo(7,3.141592653938789,bar);         /* Turbo C++ gives hard error here */

Others have mentioned that this is indeed illegal, and that casting the
address of bar() to the appropriate type will probably work but is not
guaranteed.

I would like to present a correct (I hope) alternative.  If you must call
a function through a pointer without knowing what is being returned, AND
if you are not going to USE any value returned by that function, then
you can just wrap the function inside of a function returning void.

  void bar_foo_callable(int x, double y)
  {
    (void) bar(x,y);
  }

If you DO need to use the result, then use functions that return
pointers to void.  A pointer to any object can safely be cast to a
pointer to void and subsequently cast back to a pointer to the
original type.  Of course, the original type must be known at some
higher level.
--
Steve Preston



More information about the Comp.lang.c mailing list