[英]How can you use a function pointer with argument in c?
How can you use this function pointer declaration?如何使用这个 function 指针声明?
int (* get_function(char c)) (int, int);
I have three functions int function_a(int a, int b)
, int function_b(int a, int b)
and int function_c(int a, int b)
.我有三个函数
int function_a(int a, int b)
、 int function_b(int a, int b)
和int function_c(int a, int b)
。 I want to use the above function pointer to call one of my functions conditionally based on c
.我想使用上面的 function 指针根据
c
有条件地调用我的函数之一。
Here is an example:这是一个例子:
#include <stdio.h>
int function_a(int a, int b)
{
printf("Inside function_a: %d %d\n", a, b);
return a+b;
}
int function_b(int a, int b)
{
printf("Inside function_b: %d %d\n", a, b);
return a+b;
}
int function_c(int a, int b)
{
printf("Inside function_c: %d %d\n", a, b);
return a+b;
}
int function_whatever(int a, int b)
{
printf("Inside function_whatever: %d %d\n", a, b);
return a+b;
}
int (* get_function(char c)) (int, int)
{
switch(c)
{
case 'A':
return function_a;
case 'B':
return function_b;
case 'C':
return function_c;
}
return function_whatever;
}
int main(void) {
get_function('B')(3, 5);
return 0;
}
get_function('B')
returns a function pointer to function_b
and get_function('B')(3, 5);
get_function('B')
返回一个指向function_b
和get_function('B')(3, 5);
also calls that function.也称为 function。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.