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 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;
}
                        

🖥 Program 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.

📚 Learning Subject

Master Programming Through Practical Examples

Improve your coding logic, problem-solving skills and programming confidence by practicing real-world examples with explanations.

🎯 How to learn from this example

First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.

🔥 Practice suggestion

Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.