Sunday, January 18, 2009

Function Pointer and its relation to function parameters

Its a very basic fact but an important one so mentioning it over here will help for sure.

  • A pointer to a function must have the same type as the function. Attempts to take the address of a function by reference without specifying the type of the function will produce an error.
  • The type of a function is not affected by arguments with default values.
  • The following example shows that default arguments are not considered part of a function's type. The default argument allows you to call a function without specifying all of the arguments, it does not allow you to create a pointer to the function that does not specify the types of all the arguments. Function f can be called without an explicit argument, but the pointer badpointer cannot be defined without specifying the type of the argument:

int f(int = 0);
void g()
{
int a = f(1); // ok
int b = f(); // ok, default argument used
}
int (*pointer)(int) = &f; // ok, type of f() specified (int)
int (*badpointer)() = &f; // error, badpointer and f have
// different types. badpointer must
// be initialized with a pointer to
// a function taking no arguments.

So, it means the argument should be passed of same type as argument as it was done to function.

No comments:

Post a Comment