mdh <md**@comcast.netwrites:
May I ask this.
Given the declaration:
int myf( int, int);
and a function pointer:
(*fp)=int myf(int, int);
That's not valid C, but see below.
where I am initializing fp to point at myf....or trying to..
int main (){
i=myf (3, 4);
return 0;
}
A definition of:
int myf( int a, int b){
return a+b;
}
What goes on in the workings of C when myf is called, and how does
this differ from calling myf like this?
(*fp)(3,4);
[...]
Take a look at this program, particularly the comments:
#include <stdio.h>
/* Declare myf (not really necessary here). */
int myf(int, int);
/* Define myf. */
int myf(int a, int b)
{
return a + b;
}
int main(void)
{
/* Declare fp as a pointer-to-function, of a type appropriate
* so it can point to myf.
*/
int (*fp)(int, int);
int i, j;
/* Assign a value to fp so it points to myf. */
fp = myf;
/* Call the function indirectly via the pointer. */
i = fp(2, 3);
/* Call the function directly. */
j = myf(4, 5);
/* Display the results. */
printf("i = %d, j = %d\n", i, j);
return 0;
}
A function pointer points to a function. Typically it simply contains
the memory address of the function's entry point, but that's not
specified by the language; it could contain descriptor information, or
just an index into a system table.
Calling a function via a pointer does the same thing as calling it
directly. The difference (and the reason function pointers are
useful) is that you can, by assigning different values to the function
pointer, determine at run time which function is invoked by a
different call. See the standard qsort() function for an example of
this; there's no way qsort() could call your comparison function
directly, but it can call it indirectly because you've passed a
pointer to it as an argument.
You can probably ignore the following, at least for now; I'm going to
go into some of the more abstruse aspects of the language.
An indirect function call (using a function pointer) and a direct
function call (using the function's name) are really the same thing.
Any reference to a function's name (other than as the operand of a
unary "&" or "sizeof" operator) is implicitly converted to a pointer
to the function. This conversion happens even when the name is part
of a function call. So why does the function call work? Because the
function call operator requires a function *pointer* as its first
operand. Even a direct function call uses a function pointer, one
derived from the function name. (This is very similar to the way the
array indexing operator actually requires a pointer to the array's
first element, not an array value.)
--
Keith Thompson (The_Other_Keith)
ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"