我正在处理函数指针示例,我开发了 4 个简单函数并将它们分配给一个函数指针数组,然后我运行代码并为 4 个函数工作,但后来我想也打印函数的名称。
我了解到 __func__
并且它只打印当前函数的名称,所以无论如何都可以将 __func__
分配给函数指针或其他方法来打印名称有哪些功能?
这是我现在正在处理的示例:
#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>
int add(int x, int y);
int sub(int x, int y);
int mul(int x, int y);
int divide(int x, int y);
int main() {
int m = 6;
int n = 10;
int res,i;
int (*fun[4])(int,int)={add,sub,mul,divide};
for (i=0;i<4;i++)
{
printf("result of %s operation\n",__func__=fun[i]);
}
}
int add(int x, int y) {
int result = x + y;
return result;
}
int sub(int x, int y) {
int result = x - y;
return result;
}
int mul(int x, int y) {
int result = x * y;
return result;
}
int divide(int x, int y) {
int result = x / y;
return result;
}
如您所见,我正在尝试将 __func__
分配给函数指针,但当然它不起作用。
最佳答案
每个函数中的 __func__
常量只能在运行时访问。这意味着如果你想使用那个,你必须在调用函数时捕获它。像这样:
typedef int calc_func_t (int x, int y, const char** func);
int add(int x, int y, const char** func);
...
calc_func_t* fun[4] = {add,sub,mul,divide};
for (i=0;i<4;i++)
{
const char* func;
int result = fun[i](1,1,&func);
printf("result of %s operation %d\n", func, result);
}
...
int add(int x, int y, const char** func)
{
int result = x + y;
*func = __func__;
return result;
}
...
如果您想在编译时知道函数的名称,然后在以后使用该信息,最简单和最好的方法是创建一个查找表:
typedef struct
{
calc_func_t* func;
const char* name;
} calc_func_info_t;
const calc_func_info_t func_info [] =
{
{add, "add"},
{sub, "sub"},
...
};
关于c - 如何打印函数指针的级联名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44841417/