是否可以将函数指针作为const参数传递?
我收到以下gcc错误:
警告:在'f'声明中默认为'int'[-Wimplicit-int] void execute(void(const * f)(void));
...编译此代码时:
#include <stdio.h>
void print(void);
void execute(void (const *f)(void));
int main(void)
{
execute(print); // sends address of print
return 0;
}
void print(void)
{
printf("const!");
}
void execute(void (const *f)(void)) // receive address of print
{
f();
}
这不是 What is meaning of a pointer to a constant function? 的重复,它解决了 pointers to const functions 而不是 const function argument .
2 回答
您想要的语法是:
这表示
f
是指向函数的const
指针,该函数接受void
参数并且不返回任何内容(void
) .*
右侧的const
表示 pointer 是const
. 左侧的const
表示指针 points to something ,即const
.它是
const
指针的事实意味着你不会在函数中更改f
(赋值),如果你这样做,编译器会给你一个错误 . 它没有说明函数本身 - 指向的函数在任何意义上都不是const
因为参数是const
.你写的时候:
*
左侧的const
表示指针指向的是const
,而不是指针本身是const
. 因为它说指针指向那里并且你没有列出特定类型,编译器警告你类型丢失(并且默认为int
) .The const keyword should be placed between the pointer symbol (*) and the argument name (here, f):
现在,如果您尝试更改
f
的值:...您的编译器应按预期输出类似于此错误的错误: