Function Pointer

·

1 min read

This blog has a program that uses Function Pointer to perform two different operations.

I split the code into smaller sections and explain.

The standard input output header file is included to print to the stdout.

#include <stdio.h>

This function calculates the factorial of a number

int factorial(int x)
{
    if((x==0) || (x==1))
    {
        return 1;
    }
    else
    {
        return x*factorial(x-1);
    }
}

Next is another function to calculate the triangle value of a number. A triangle number is the equivalent of a multiplicative factorial but with addition.

int triangleNumber(int x)
{
    if(x==0)
    {
        return 0;
    }
    else if(x==1)
    {
        return 1;
    }
    else
    {
        return x+triangleNumber(x-1);
    }
}

The main function declares a function pointer with the syntax of the function that is to be assigned to it. Calling the function pointer will eventually invoke the assigned function.


void main()
{
    int (*functionPointer)(int x);

    functionPointer = triangleNumber;
    printf("triangleNumber of 7:%d\n", functionPointer(7));
    functionPointer = factorial;
    printf("Factorial of 7:%d\n", functionPointer(7));
}

The output is

💡
TriangleNumber of 7:28
💡
Factorial of 7:5040