Open In App

Returning a function pointer from a function in C/C++

Last Updated : 11 Mar, 2023
Comments
Improve
Suggest changes
4 Likes
Like
Report

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++

Output
30

 
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++

Output
Hello geeks!!
20

 
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++

Output
Hello geeks!!
20


 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:


Output
9

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++:


Output
Result: 7

Next Article

Similar Reads