Home / Programs / A function pointer can be used in place of switch case
Programming Example

A function pointer can be used in place of switch case

👁 1,069 Views
💻 Practical Program
📘 Step by Step Learning
Interesting facts about function pointers

Program Code

#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.

How to learn from this program

First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.