Re: Cannot understand the following codes




On Wed, 29 Mar 2006, Ben C wrote:
On 2006-03-29, Joe Wright <joewwright@xxxxxxxxxxx> wrote:
Ben C wrote:
[..]
I had assumed void * was good for anything. But it's only good for data,
not functions.

I suppose on some machines functions might have a completely different
address space, be a completely different size etc., and the standard is
allowing for that...

Pedantically void pointers and function pointers are not compatible.
But is a less pedantic world it might work.. if you change your line

int x = (*r)(3);

to

int x = (r)(3); or even

int x = r(3);

Isn't this a different issue? I don't know what the standard says about
r(3), although it usually works.

It is a different issue altogether. Changing (*r) to (r) won't magically make the difference (in C) between data and code pointers go away.

The difference between (*r) and (r) is that (*r) is the thing pointed to by 'r', which is of function type, which, in this context, immediately
decays back to a function pointer. (r) is just that same function pointer, without the dereference and decay. In other words, (*r) decays to (r).
Therefore, both expressions have the /exact same/ behavior.


I think more old code used the (*f)(x) style, and newer code, maybe influenced by C++ and Lispy languages, uses plain old f(x) more often.
I tend to use (*cmp)(x,y) for callback functions in things like 'qsort', but if I were writing something like

int (*printme)() = (widget == on)? magic: more_magic;

I'd use

printme(x);

instead.

HTH,
-Arthur
.



Relevant Pages

  • Re: function pointer tutorial may be helpful..
    ... A function pointer is a value that is the address of a function. ... static int my_function ... void young; ...
    (comp.lang.c)
  • Re: returning function pointer
    ... function pointer some_func & meanwhile calls that function and prints ... void some_func ... int main ... Note there are two parameter lists here. ...
    (comp.lang.c)
  • Re: Casting pointers to functions of different types
    ... you will receive an error message from the compiler. ... Code which stored function pointer in array of unsigned ... typedef void; ... void marshal (AFunc func, int *args) ...
    (comp.lang.c)
  • Casting pointers to functions of different types
    ... It has to cast a function pointer to some ... Code which stored function pointer in array of unsigned ... typedef void; ... void marshal (AFunc func, int *args) ...
    (comp.lang.c)
  • Re: get the address of a function??
    ... void hello ... Calling printf with no visible prototype invokes undefined behavior. ... Make it "int main". ... *But* there's no defined conversion from a function pointer to void* ...
    (comp.lang.c)