program to explain function pointers.

29 Dec 2022 Balmiki Kumar 0 C Programming

Unlocking the Power of Function Pointers: Practical C Programming

Function pointers are pointers that point to the address of functions. They allow you to store the address of a function and later call that function through the pointer. This can be particularly useful when you want to choose which function to call at runtime or when you want to pass functions as arguments to other functions.

C program that explains function pointers:

C Programming
#include <stdio.h>

// Function prototypes
int add(int a, int b);
int subtract(int a, int b);

int main() {
    // Declare function pointers
    int (*operation)(int, int);

    // Assign function addresses to function pointers
    operation = add;
    
    int result = operation(5, 3);  // Call add function through the pointer
    printf("Addition result: %d\n", result);

    operation = subtract;
    
    result = operation(8, 4);  // Call subtract function through the pointer
    printf("Subtraction result: %d\n", result);

    return 0;
}

// Function definitions
int add(int a, int b) {
    return a + b;
}

int subtract(int a, int b) {
    return a - b;
}

 

In this program:

  1. We include the standard input/output header stdio.h.

  2. We declare two function prototypes: add and subtract.

  3. In the main function:

    • We declare a function pointer operation that can point to functions taking two int arguments and returning an int.
    • We assign the address of the add function to the operation pointer and use it to call the add function.
    • We then reassign the operation pointer to point to the subtract function and use it to call the subtract function.
  4. Below the main function, we define the add and subtract functions as specified in the prototypes.

When you run this program, you'll see the following output:

Addition result: 8
Subtraction result: 4

In this example, we've demonstrated how to use function pointers to dynamically choose and call different functions based on the function pointer assignments. The operation pointer acts as a switch, allowing us to call different functions using the same pointer.

BY: Balmiki Kumar

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.