Function pointers - The unconventional use

In my previous post about function pointers, I have written about the definition of function pointers. Which explains how to avoid confusions while defining. In this post, I will list some uses of the function pointer.

The unconventional use

Usually function pointer are used in callbacks or some special cases. But, we can use it also to simplify code. Consider the below example
void print_zero(void)
{
    printf("Zero\n");
}
void print_one(void)
{
    printf("One\n");
}
void print_two(void)
{
    printf("Two\n");
}
void print_three(void)
{
    printf("Three\n");
}
void print_four(void)
{
    printf("Four\n");
}
void example_switch(void)
{
    unsigned int number = 0;

    switch(number)
    {
        case 0:
            print_zero();
            break;
        case 1:
            print_one();
            break;
        case 2:
            print_two();
            break;
        case 3:
            print_three();
            break;
        case 4:
            print_four();
            break;
        default:
            break;
    }
    
}
The snippet above is nothing but calling few functions in a switch case. Using function pointers, it can be simplified as below.
void example_fPtr(void)
{
    unsigned int number = 0;
    void (*pFun[5])(void) = { /* Define and initialize function pointer */
        print_zero, print_one, print_two, print_three, print_four
    };
    
    number = 4;
    if(number < 5)
        pFun[number](); /* Call function corresponding to number */
}

No comments :

Post a Comment