Electro4u 28 Dec 2022 4 views 0 comments C Programming

program to explain function pointers.

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.

0 Comments

No comments yet, Be the first to comment.

Post a Comment

Please sign in to post a comment.

Related Posts

Bit wise operators Assignment

Bitwise Operators practical assignment: Take runtime input, bit-level manipulation, and different data units r...

AG Anvesh G 27 Sep 2026
Understanding Float and Double Binary Representation in C

Understanding Float and Double Binary Representation in CIntroduction:When we store decimal numbers such as 10...

AG Anvesh G 31 May 2026
Topic-wise C Programming Interview Questions

C Programming Interview Questions – Topic Wise1. IntroductionC programming is one of the most important langu...

AG Anvesh G 30 May 2026