C Language Function Pointers Basics


Example

Just like you can have a pointer to an int, char, float, array/string, struct, etc. - you can have a pointer to a function.

Declaring the pointer takes the return value of the function, the name of the function, and the type of arguments/parameters it receives.

Say you have the following function declared and initialized:

int addInt(int n, int m){
    return n+m;
}

You can declare and initialize a pointer to this function:

int (*functionPtrAdd)(int, int) = addInt; // or &addInt - the & is optional

If you have a void function it could look like this:

void Print(void){
    printf("look ma' - no hands, only pointers!\n");
}

Then declaring the pointer to it would be:

void (*functionPtrPrint)(void) = Print;

Accessing the function itself would require dereferencing the pointer:

sum = (*functionPtrAdd)(2, 3); //will assign 5 to sum
(*functionPtrPrint)(); //will print the text in Print function

As seen in more advanced examples in this document, declaring a pointer to a function could get messy if the function is passed more than a few parameters. If you have a few pointers to functions that have identical "structure" (same type of return value, and same type of parameters) it's best to use the typedef command to save you some typing, and to make the code more clear:

typedef int (*ptrInt)(int, int);

int Add(int i, int j){
    return i+j;
}

int Multiply(int i, int j){
    return i*j;
}

int main()
{
    ptrInt ptr1 = Add;
    ptrInt ptr2 = Multiply;

    printf("%d\n", (*ptr1)(2,3)); //will print 5
    printf("%d\n", (*ptr2)(2,3)); //will print 6
    return 0;
}

You can also create an Array of function-pointers. If all the pointers are of the same "structure":

int (*array[2]) (int x, int y); // can hold 2 function pointers
array[0] = Add;
array[1] = Multiply;

You can learn more here and here.

It is also possible to define an array of function-pointers of different types, though that would require casting when-ever you want to access the specific function. You can learn more here.