Summary: This program performs basic arithmetic operations (+, -, *, /) using function pointers. The operation to be performed is selected based on user input and invoked through the function pointer.
#include <stdio.h>
int add(int a, int b) { return a + b; }
int subtract(int a, int b) { return a - b; }
int multiply(int a, int b) { return a * b; }
int divide(int a, int b) {
if (b != 0) return a / b;
printf("Error: Division by zero.\n");
return 0;
}
int main() {
int a, b;
char op;
int (*operation)(int, int);
printf("Enter two numbers: ");
scanf("%d %d", &a, &b);
printf("Select operation (+, -, *, /): ");
scanf(" %c", &op);
switch (op) {
case '+': operation = add; break;
case '-': operation = subtract; break;
case '*': operation = multiply; break;
case '/': operation = divide; break;
default:
printf("Invalid operation.\n");
return 1;
}
int result = operation(a, b);
printf("Result: %d\n", result);
return 0;
}
Function Pointer Declaration:
The program uses a function pointer operation that can point to any arithmetic function matching the signature int func(int, int).
User Input & Dispatch:
Based on the user’s choice of operator, the function pointer is assigned the appropriate function using a switch statement.
Calling via Pointer:
The actual operation is performed through the pointer: operation(a, b), making the logic reusable and dynamic.
Division Safety:
The divide function checks for division by zero to prevent runtime errors.
Flexibility:
Using function pointers simplifies expanding the program to more operations in the future by simply adding more functions and cases.