WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

C · Advanced · question 44 of 100

Explain how to use function pointers in C, and provide an example.?

📕 Buy this interview preparation book: 100 C questions & answers — PDF + EPUB for $5

In C programming, function pointers are variables that store the memory address of a function. They can be used to call a function indirectly and are often used to implement callbacks and function arrays.

Here’s an example of how to use function pointers in C:

    #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 main() {
        int a = 10, b = 5;
        int (*func_ptr)(int, int); // declare function pointer variable
        
        // assign function pointer to the 'add' function
        func_ptr = &add;
        
        // call the 'add' function through the function pointer
        int result = (*func_ptr)(a, b);
        printf("Result: %dn", result);
        
        // assign function pointer to the 'subtract' function
        func_ptr = &subtract;
        
        // call the 'subtract' function through the function pointer
        result = (*func_ptr)(a, b);
        printf("Result: %dn", result);
        
        // assign function pointer to the 'multiply' function
        func_ptr = &multiply;
        
        // call the 'multiply' function through the function pointer
        result = (*func_ptr)(a, b);
        printf("Result: %dn", result);
        
        return 0;
    }

In this example, we define three functions add, subtract, and multiply, which take two integers as arguments and return an integer value. We then declare a function pointer variable func_ptr that takes two integers as arguments and returns an integer value.

We first assign func_ptr to the add function using the & operator to get the address of the function. We then call the add function indirectly using the function pointer (*func_ptr)(a, b).

We then reassign func_ptr to the subtract function and call it using the function pointer, and finally, we reassign func_ptr to the multiply function and call it again.

This is just one example of how function pointers can be used in C. They are a powerful feature of the language that can be used to implement a wide variety of functionality, from callbacks to function arrays to dynamic function calls.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic C interview — then scores it.
📞 Practice C — free 15 min
📕 Buy this interview preparation book: 100 C questions & answers — PDF + EPUB for $5

All 100 C questions · All topics