Friday, November 5, 2010

quick note on function pointers

I think I just figured something out.

Ok.

int *my_function(int x, float y)

This is a function that returns a pointer to an integer.

int (*my_function)(int x, float y)

This is a pointer to a function that returns an integer. I got tripped up by the part (int x, float y) that makes it look like you're making the function prototype - but really this is just C wanting you to be really precise about what you want to be done. I wonder if this is 100% necessary - further experimentation is needed.

Another important note: remember that pointers need to be initialized.

I need to say at some time:

my_function = &some_function

where some_function is:

some_function(int x, float y)

1 comment:

  1. And now for a peek under the hood!

    You can also write:

    int (*my_function)(int,float)

    All the compiler needs to know is that your function pointer points to "any function in the family of functions" that have a first argument of type 'int' and a second argument of type 'float'.

    1) Now, when you make an assignment to your function pointer:

    my_function = &some_function;

    ... the compiler knows to check that 'some_function' has the same "fingerprint" (int, float) as 'my_function'.

    2) When you call (dereference) your function pointer:

    *my_function(42, 27.0);

    ... the compiler does not know at compile time what function will actually be called, but it knows that it must make room on the stack for the two arguments you told it about (int,float).

    Recall that function arguments are simply local variables that are created when the function is called. Because the compiler made sure that any function reference you assigned to your pointer had the right "fingerprint" (#1), that function (some_function) will know exactly where and how to find its two arguments.

    ReplyDelete