Function Pointers

Allow functions to be assigned (and therefore reassigned) to pointers, assuming the signature following the pointer is the same.

 

int (*funcPtr) (int) ;

 

In the above example, funcPtr is a function pointer that returns an int, takes an int parameter and can point to any function that matches this signature.

 

The pointer should be enclosed within parentheses to ensure it is recognised as a pointer, due to the rules of operator precedence whereby parentheses are of higher precedence than *.

 

int (*funcPtr)() = funcOne ;  //declares a pointer that points to funcOne - Notice NO parentheses being used on the function being pointed to!

 

In this case, funcPtr now points to the funcOne function and can be reassigned to point to another function, as long as it uses the same signature.

 

In this example a function pointer has been created that points to functions that take one parameter in their signature:

#include <iostream>
using namespace std;

#define MODIFIER 7

int funcOne(int myVar){

	int x = myVar / MODIFIER  ;

	return x ;
}

int funcTwo(int myVar){

	int x = myVar * MODIFIER  ;

	return x ;
}

int main() {

	int (*funcPtr)(int) ;  //create an int function pointer

	funcPtr = funcOne ;  //assign it to a function

	cout << funcPtr(63) << endl ; //use function pointer

	funcPtr = funcTwo ;  //reassign to another function

	cout << funcPtr(5) << endl ; //use function pointer

    return 0;
}

Compile & Run:

9
35

Leave a Reply