• Home
  • 6.17 Function Pointers

6.17 Function Pointers

View Categories

6.17 Function Pointers

1 min read

Table of Contents

A function pointer is a pointer that stores the address of a function. It allows a function to be called indirectly through the pointer instead of using its name directly.

The type of a function pointer is determined by the function’s return type and parameter types. Function pointers are useful when a program needs to select or pass functions dynamically, such as implementing callbacks or dispatch tables.

Source Code #

#include <iostream>

int add(int first, int second)
{
    return first + second;
}

int main()
{
    int (*operation)(int, int) = add;

    int result = operation(10, 20);

    std::cout << "Result: " << result << '\n';

    return 0;
}

Output #

Result: 30

Explanation #

  • int (*operation)(int, int) declares operation as a pointer to a function.
  • The pointer can point to a function that returns int and accepts two int parameters.
  • = add initializes the function pointer with the address of the add() function.
  • operation(10, 20) calls the function through the function pointer.
  • The function pointer call produces the same result as directly calling add(10, 20).
  • The function’s return type and parameter types must be compatible with the function pointer’s type.
  • Function pointers can be passed to other functions and used to select different functions at runtime.
  • return 0; terminates the program successfully.

Powered by BetterDocs

Leave a Reply

Your email address will not be published. Required fields are marked *