Returning a function pointer from a function in C/C++
Last Updated :
11 Mar, 2023
In C/ C++, like normal data pointers(int *, char *, etc), there can be pointers to functions. Every function created in a program gets an address in memory since pointers can be used in C/C++, so a pointer to a function can also be created.
Syntax:
return type (*function_pointer_name) (argument_type_1, argument_type_2, ......, argument_type_n) = &function_name;
OR
return type (*function_pointer_name) (argument_type_1, argument_type_2, ......, argument_type_n) = function_name;
NOTE: Arguments type and return type of function pointer should match with the actual function present in the program.
Program 1:
C
// C program for the above approach
#include <stdio.h>
// Function to add the value 10 to
// the variable a
void demo(int* a) { *a += 10; }
// Driver Code
int main()
{
int num = 20;
// ptr contains address of demo
// function or void
void (*ptr)(int*) = &demo;
// or (*ptr)(&num);
ptr(&num);
printf("%d", num);
return 0;
}
C++
// C++ program for the above approach
#include <iostream>
using namespace std;
void demo(int& a)
{
a += 10;
}
// Driver Code
int main()
{
int num = 20;
// Now ptr contains address of demo
// function or void
void (*ptr)(int*) = &demo;
// or (*ptr)(num);
ptr(num);
cout << num << endl;
return 0;
}
Return Function Pointer From Function: To return a function pointer from a function, the return type of function should be a pointer to another function. But the compiler doesn't accept such a return type for a function, so we need to define a type that represents that particular function pointer.
Syntax :
typedef return type (*function_pointer_name) (argument_type_1, argument_type_2, ......, argument_type_n);
This creates a type which represents a pointer for a particular function.
Program 2:
C
// C program for the above approach
#include <stdio.h>
typedef int (*ptr)(int*);
typedef ptr (*pm)();
int fun1(int* y)
{
printf("geeks!!\n");
return *y + 10;
}
// Function that return type ptr
ptr fun()
{
printf("Hello ");
// or return fun1;
/* or
int(*pt)(int*)=fun1;
return pt
*/
return &fun1;
}
// Driver Code
int main()
{
int a = 10;
pm u = fun;
printf("%d", (*u())(&a));
return 0;
}
C++
// C++ program for the above approach
#include <iostream>
using namespace std;
typedef int (*ptr)(int*);
typedef ptr (*pm)();
int fun1(int* y)
{
cout << "geeks!!" << endl;
return *y + 10;
}
// Function that returns the type ptr
ptr fun()
{
cout << "Hello ";
return &fun1;
}
// Driver Code
int main()
{
int a = 10;
pm u = fun;
cout << (*u())(&a) << endl;
return 0;
}
Declaring an array that has two function pointers as to its elements and these function pointers, in turn, return other function pointers which point to other functions. The logic of the driver code main() function can be changed in the above program as:
Program 3:
C
// C program for the above approach
#include <stdio.h>
// This defines a type for
// function prototypes
typedef int (*ptr)(int*);
typedef ptr (*pm)();
int fun1(int* y)
{
printf("geeks!!\n");
return *y + 10;
}
// fun() is a function with
// return type ptr
ptr fun()
{
printf("Hello ");
// or return fun1;
/* or
int(*pt)(int*)=fun1;
return pt
*/
return &fun1;
}
// Driver code
int main()
{
int a = 10;
pm u = fun;
/*
Above line assigns 'u' which is
of type 'pm' to an array of size
1 which has function pointers as
its elements and these function
pointers in turn return other
function pointer which points to
other functions.
Now this 'p' array contains a function
pointer 'u' which points to fun() and
this fun() returns another function
pointer which points to fun1().
*/
int (*(*p[1])())(int*) = { u };
printf("%d", (*p[0]())(&a));
}
C++
// C++ program for the above approach
#include <iostream>
using namespace std;
// This defines a type for
// function prototypes
typedef void (*ptr)(int&);
typedef ptr (*pm)();
void fun1(int& z)
{
printf("geeks!!\n");
cout << z + 10 << endl;
}
// Function that returns type ptr
ptr fun()
{
printf("Hello ");
// or return fun1;
/* or
int(*pt)(int*)=fun1;
return pt
*/
return &fun1;
}
// Driver Code
int main()
{
int a = 10;
pm u = fun;
/*
Above line assigns 'u' which is
of type 'pm' to an array of size
1 which has function pointers as its
elements and these function pointers
in turn return other function pointer
which points to other functions.
Now this 'p' array contains a function
pointer 'u' which points to fun() and
this fun() returns another function
pointer which points to fun1() and
this fun1() returns void.
*/
void (*(*p[1])())(int&) = { u };
(*p[0]())(a);
}
In both C and C++, you can return a function pointer from a function by declaring the return type of the function as a pointer to a function.
Here's an example in C:
C
#include <stdio.h>
int add(int a, int b) {
return a + b;
}
int subtract(int a, int b) {
return a - b;
}
int (*operation(char op))(int, int) {
if (op == '+') {
return &add;
} else if (op == '-') {
return &subtract;
} else {
return NULL;
}
}
int main() {
int (*func_ptr)(int, int) = operation('+');
printf("%d\n", func_ptr(4, 5));
return 0;
}
In this example, we have two functions called add() and subtract() that take two integer arguments and return an integer value. We also have a function called operation() that takes a character argument op and returns a function pointer to add() or subtract() depending on the value of op. Finally, in main(), we call operation() with '+' as the argument and store the result in a function pointer called func_ptr. We then call func_ptr() with 4 and 5 as arguments and print the result to the console.
Here's the same example in C++:
C++
#include <iostream>
using namespace std;
int add(int a, int b) {
return a + b;
}
int subtract(int a, int b) {
return a - b;
}
int (*get_operation(char op))(int, int) {
if (op == '+') {
return &add;
} else if (op == '-') {
return &subtract;
} else {
return NULL;
}
}
int main() {
int (*op)(int, int) = get_operation('+');
int result = op(3, 4);
cout << "Result: " << result << endl;
return 0;
}
Similar Reads
How to Return a Pointer from a Function in C++?
In C++, we can return a pointer from a function which is useful when we want to return large data structures that cannot be returned by value. However, it must be done carefully to avoid memory leaks, dangling pointers, and other issues related to dynamic memory management. In this article, we will
2 min read
Function Pointer to Member Function in C++
In C++, function pointers enable users to treat functions as objects. They provide a way to pass functions as arguments to other functions. A function pointer to a member function is a pointer that points to a non-static member function of a class. In this article, we will learn how to use a functio
3 min read
How to Create a Pointer to a Function in C++?
In C++, a function pointer is a variable that stores the address of a function that can later be called through that function pointer. It is useful for passing functions as parameters to other functions(callback functions) or storing them in data structures. In this article, we will learn how to use
2 min read
How to Create a Typedef for a Function Pointer in C?
In C, a function pointer is a variable that stores the address of a function that can later be called through that function pointer. The typedef is a keyword used to create an alias or alternative name for the existing data types. In this article, we will learn how to create a typedef for a function
2 min read
When to Use a Functor Instead of a Function in C++?
In C++, both functors and functions can be used to encapsulate behavior and provide callable objects. Still, there are specific scenarios where using a functor is more advantageous than a regular function. In this article, we will learn when to use a functor instead of a function in C++. When to Pre
4 min read
How to Return a Vector From a Function in C++?
In C++, by returning vectors, users to return multiple values at once from a function as the elements of vector. In this article, we will learn how to return a vector from a function in C++.The recommended way to return a vector from a function is by using return vector by value method. Letâs take a
3 min read
How to call function within function in C or C++
When we begin programming in C/C++, we generally write one main() function and write all our logic inside this. This approach is fine for very small programs, but as the program size grows, this become unmanageable. So we use functions. We write code in the form of functions. The main function alway
4 min read
Passing a Function as a Parameter in C++
Passing a function as an argument is useful in dynamically changing the behaviour of the function. This concept has already been used while passing a custom comparator function as an argument in sort() function to sort a sequence of objects as per the need.Function that is passed as argument is call
4 min read
How to Call a Virtual Function From a Derived Class in C++?
In C++, virtual functions play an important role because they allow the users to perform run-time polymorphism. While dealing with inheritance and virtual functions, it is very crucial to understand how to call a virtual function from a derived class. In this article, we will learn how to call a vir
2 min read
Calling a non-member function inside a class in C++
Member Function: It is a function that can be declared as members of a class. It is usually declared inside the class definition and works on data members of the same class. It can have access to private, public, and protected data members of the same class. This function is declared as shown below:
3 min read