C Function Pointer

A function pointer in C is a pointer that points to a function rather than a data value (like an integer or a character). This means the pointer holds the memory address of a function.

Function pointers are useful because they allow you to call a function indirectly, pass functions as arguments to other functions, or even return functions from other functions.

Syntax:


return_type (*pointer_name)(parameter_types);

Explanation:

  • return_type: The return type of the function the pointer will point to.
  • pointer_name: The name of the pointer.
  • parameter_types: The types of parameters the function accepts.

Example:


#include <stdio.h>

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

int main() {
    // Declare a function pointer
    int (*fun_ptr)(int, int);

    // Assign the function pointer to the function
    fun_ptr = add;

    // Call the function using the pointer
    int result = fun_ptr(10, 20);  // Equivalent to add(10, 20)
    printf("Result: %d\n", result);  // Output: 30

    return 0;
}

Output:

30

Explanation:

  • int (*fun_ptr)(int, int); declares fun_ptr as a pointer to a function that takes two int arguments and returns an int.
  • fun_ptr = add; assigns the address of the add function to the function pointer fun_ptr.
  • fun_ptr(10, 20) calls the function add(10, 20) via the function pointer.

C Function Pointer – Questions and Answers

Q 1: What is a function pointer?

Ans: A pointer that stores the address of a function.

Q 2: Why are function pointers used?

Ans: For callback functions and dynamic function calls.

Q 3: How do you declare a function pointer?

Ans: int (*fp)(int, int);

Q 4: Can function pointers be passed as arguments?

Ans: Yes.

Q 5: Where are function pointers commonly used?

Ans: In event handling and libraries like qsort().

C Function Pointer – Objective Questions (MCQs)

Q1. What is a function pointer in C?






Q2. Which of the following is the correct declaration of a function pointer?






Q3. How can you call a function using a function pointer fptr?






Q4. What is the main use of function pointers?






Q5. What is the output of:

void display() { printf("Hello"); }
int main() {
void (*fptr)() = display;
fptr();
}






Related C Function Pointer Topics