0
0
CHow-ToBeginner · 3 min read

How to Use Function Pointer in C: Syntax and Example

In C, a function pointer stores the address of a function and can be used to call that function indirectly. You declare it by specifying the return type and parameter types, then assign it to a function name without parentheses. Calling the function through the pointer uses the pointer name with arguments like a normal function call.
📐

Syntax

A function pointer declaration includes the return type, the pointer name in parentheses with an asterisk, and the parameter types in parentheses.

  • Return type: The type of value the function returns.
  • Pointer name: The name of the function pointer variable.
  • Parameter types: The types of arguments the function accepts.

Example syntax:

c
return_type (*pointer_name)(parameter_types);
💻

Example

This example shows how to declare a function pointer, assign it to a function, and call the function through the pointer.

c
#include <stdio.h>

// A simple function that adds two integers
int add(int a, int b) {
    return a + b;
}

int main() {
    // Declare a function pointer that points to a function taking two ints and returning int
    int (*func_ptr)(int, int);

    // Assign the function pointer to the 'add' function
    func_ptr = add;

    // Call the function using the pointer
    int result = func_ptr(5, 3);

    printf("Result of add(5, 3) using function pointer: %d\n", result);
    return 0;
}
Output
Result of add(5, 3) using function pointer: 8
⚠️

Common Pitfalls

  • Forgetting to use parentheses around the pointer name in the declaration, which changes the meaning.
  • Assigning a function pointer to a function with a different signature (return type or parameters).
  • Calling a function pointer without initializing it first, leading to undefined behavior.
  • Using the function name with parentheses when assigning to the pointer (use the function name without parentheses).

Example of wrong and right declaration:

c
// Wrong: pointer_name is a function returning int, not a pointer
int func_ptr_wrong(int, int);

// Right: func_ptr is a pointer to a function returning int
int (*func_ptr_right)(int, int);
📊

Quick Reference

ConceptExample
Declare function pointerint (*fp)(int, int);
Assign function to pointerfp = add;
Call function via pointerint result = fp(2, 3);
Function pointer with void returnvoid (*fp_void)(void);
Pointer to function with no parametersint (*fp_no_param)(void);

Key Takeaways

Declare function pointers with parentheses around *pointer name to avoid syntax errors.
Assign function pointers using the function name without parentheses.
Call functions through pointers just like normal functions using the pointer name and arguments.
Always ensure the function pointer signature matches the function's return and parameter types.
Initialize function pointers before calling to prevent undefined behavior.