⇐ MY QUORA-INDEX QUORA - my answered Questions

QUORA - my answered Questions

Q030: How do function pointers work in C and C++, and what are some examples?

I will give you a simple example for C language. There are two functions, foo and bar which will be invoked indirectly by the function named call().
#include <stdio.h>

static void foo(void) {
		   printf("foo invoked\n");
}
static void bar(void) {
   printf("bar invoked\n");
}
static void call(void (*callback)(void)){
// Declaration of function pointer callback:
// void              (*callback)        (void)
// no return value   function pointer   no argument
   callback(); // invoking the function pointer now
}
int main() {
	   call(foo); /* foo without parenthesis means function pointer.
               * this is the address of the function, not the
               * function call itself. the function might be
               * called later and probably multiple times */
   call(bar); // same semantic as foo, but different function

   return 0;
}