0
0
CppHow-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 function's return type and parameter types, then assign it to a function name without parentheses. Calling the function pointer uses the same syntax as calling a regular function.
📐

Syntax

To declare a function pointer, specify the return type, then use parentheses with an asterisk and the pointer name, followed by the parameter types in parentheses.

  • Return type: The type the function returns (e.g., int).
  • Pointer name: The name of the function pointer variable.
  • Parameter types: The types of parameters the function accepts.

Example syntax:

cpp
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.

cpp
#include <iostream>

// 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 (*funcPtr)(int, int) = nullptr;

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

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

    std::cout << "Result of add(5, 3) using function pointer: " << result << std::endl;

    return 0;
}
Output
Result of add(5, 3) using function pointer: 8
⚠️

Common Pitfalls

  • Forgetting to match the function pointer's signature exactly with the function's signature causes errors.
  • Using parentheses incorrectly when declaring the pointer (missing parentheses around *pointer_name).
  • Calling the function pointer without initializing it first leads to undefined behavior.
  • Assigning a function pointer to a function with a different return type or parameters causes compilation errors.

Example of wrong and right declaration:

cpp
// Wrong: missing parentheses around *funcPtr
int *funcPtr(int, int); // Declares a function returning int* instead of a pointer to function

// Right:
int (*funcPtr)(int, int); // Pointer to function returning int
📊

Quick Reference

ConceptExample
Declare function pointerint (*funcPtr)(int, int);
Assign function pointerfuncPtr = add;
Call function via pointerint result = funcPtr(5, 3);
Function pointer with no parametersvoid (*funcPtr)();
Null pointer initializationfuncPtr = nullptr;

Key Takeaways

Declare function pointers with matching return and parameter types using parentheses around *pointer_name.
Assign function pointers by using the function name without parentheses.
Call the function through the pointer using the same syntax as a normal function call.
Always initialize function pointers before calling to avoid undefined behavior.
Function pointers enable flexible code by allowing indirect function calls.