A function pointer can be used in place of switch case

C Programming Language / Pointer in C Language

971

Program:

#include <stdio.h>
void add(int a, int b)
{
    printf("Addition is %d\n", a+b);
}
void subtract(int a, int b)
{
    printf("Subtraction is %d\n", a-b);
}
void multiply(int a, int b)
{
    printf("Multiplication is %d\n", a*b);
}
 
int main()
{
    // fun_ptr_arr is an array of function pointers
    void (*fun_ptr_arr[])(int, int) = {add, subtract, multiply};
    unsigned int ch, a = 15, b = 10;
 
    printf("Enter Choice: 0 for add, 1 for subtract and 2 "
            "for multiply\n");
    scanf("%d", &ch);
 
    if (ch > 2) return 0;
 
    (*fun_ptr_arr[ch])(a, b);
 
    return 0;
}

Output:

Enter Choice: 0 for add, 1 for subtract and 2 for multiply
2
Multiplication is 150 

Explanation:

Like normal pointers, we can have an array of function pointers. Below example in next point shows syntax for array of pointers.

Function pointer can be used in place of switch case. For example, in this program, user is asked for a choice between 0 and 2 to do different tasks.


This Particular section is dedicated to Programs only. If you want learn more about C Programming Language. Then you can visit below links to get more depth on this subject.