Question

What are Function Pointers in plain English?

Was it helpful?

Solution

In simple english,

A FUNCTION_POINTER is a pointer which points towards the address of fuction's first instruction, like a POINTER which points towards the address of a variable.

Take a example of a program to understand the concept

Sum of all integers upto the user i/p

-

#include <stdio.h>

int IsAny(long n)
{
    return 1;
}

long AddIf(long limit, int (*funPointer)(long))
{
    long sum = 0;
    register int i;

    for(i = 1; i <= limit; ++i)
    {
        if(funPointer(i))
            sum += i;
    }

    return sum;
}

int main(void)
{
    long l, total;

    printf("Enter a positive integer: ");
    scanf("%ld", &l);

    total = AddIf(l, IsAny);
    printf("Sum of all integers upto %ld is %ld\n", l, total);
}

Here FUNCTION_POINTER is called to call IsAny function in AddIf with a declaration as int (*funPointer)(long)) in AddIf function

OTHER TIPS

As you asked in plain english, let's give it a try.

A pointer is an address in memory. A pointer has a type so the program can "find" the object you are refering to when using your pointer.

A function pointer uses the same logic. It declares a function that will be used has a method parameter for exemple. So you know that you will use a function that will have an input and an ouput in that method but the logic in that function don't need to be known.

From there you can send any function pointer to be used as the program only concern is that you will send and receive predefined types.

According wiki

A function pointer (or subroutine pointer or procedure pointer) is a type of pointer supported by third-generation programming languages (such as PL/I, COBOL, Fortran,1 dBASE dBL, and C) and object-oriented programming languages (such as C++ and D).2 Instead of referring to data values, a function pointer points to executable code within memory. When dereferenced, a function pointer can be used to invoke the function it points to and pass it arguments just like a normal function call. Such an invocation is also known as an "indirect" call, because the function is being invoked indirectly through a variable instead of directly through a fixed name or address. Function pointers can be used to simplify code by providing a simple way to select a function to execute based on run-time values.

Pointer = That hold the address of a variable or means simple memory. As same like pointer , function pointer that hold the address of a function.

Syntax : return type (*fp) (argument);

Example:

void f1()
    {
      printf("in function f1");
    }
int main()
{
  /* declaring a function pointer
   * argument void 
   * return type is also void
   */

  void (*fun_ptr) (void);  
  fun_pt= f1();  // fun_pthold the address of f1
  (*fun_pt)();    // calling a function f1 
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top