我想显示我正在调用的函数的名称.这是我的代码
void (*tabFtPtr [nbExo])(); // Array of function pointers
int i;
for (i = 0; i < nbExo; ++i)
{
printf ("%d - %s", i, __function__);
}
Run Code Online (Sandbox Code Playgroud)
我用它__function__作为一个例子,因为它与我想要的非常接近,但我想显示指向的函数的名称tabFtPtr [nbExo].
谢谢你帮助我:)
Lun*_*din 31
您需要一个遵循C99标准或更高版本的C编译器.有一个预先定义的标识符__func__,它可以满足您的要求.
void func (void)
{
printf("%s", __func__);
}
Run Code Online (Sandbox Code Playgroud)
编辑:
作为一个奇怪的参考,C标准6.4.2.2规定上述内容与您明确写明的内容完全相同:
void func (void)
{
static const char f [] = "func"; // where func is the function's name
printf("%s", f);
}
Run Code Online (Sandbox Code Playgroud)
编辑2:
因此,为了通过函数指针获取名称,您可以构造如下内容:
const char* func (bool whoami, ...)
{
const char* result;
if(whoami)
{
result = __func__;
}
else
{
do_work();
result = NULL;
}
return result;
}
int main()
{
typedef const char*(*func_t)(bool x, ...);
func_t function [N] = ...; // array of func pointers
for(int i=0; i<N; i++)
{
printf("%s", function[i](true, ...);
}
}
Run Code Online (Sandbox Code Playgroud)