I have been trying to understand a post from geeksforgeeks and am not able to understand a code snippet. Here is the following post:
https://www.geeksforgeeks.org/returning-a-function-pointer-from-a-function-in-c-cpp/
In this post they give and example code as the following:
Based on the following code
#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;
}
I'm not understanding how a function be declared like this. Based on my knowledge of function pointers, a function pointer can be declared as such:
int func(int x, int y){
return x*y;
}
int (*func_ptr) (int, int);
func_ptr = &func;
The description is not very clear as well from the post:
"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."
Any help would be appreciated!
Well, it's just how the C syntax works when you want to return a function pointer.
Not sure if this will make it more clear but it tries to explain what the individual parts of the statement means:
int (*operation(char op))(int, int)
\-------/
Name of this function
int (*operation(char op))(int, int)
\-------/
Arguments for this function
int (*operation(char op))(int, int)
^^ ^^ ^
This function returns a function pointer
int (*operation(char op))(int, int)
\---------/
The argument types taken by the function the
function pointer points to.
int (*operation(char op))(int, int)
\-/
The return type of the function the function pointer points to.
The syntax can be simplified using a typedef like:
typedef int (*func_pointer)(int, int);
func_pointer operation(char op) {
...
}