首页 文章

函数指针作为const参数

提问于
浏览
3

是否可以将函数指针作为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 回答

  • 2

    您想要的语法是:

    void execute(void (* const f)(void));
    

    这表示 f 是指向函数的 const 指针,该函数接受 void 参数并且不返回任何内容( void ) . * 右侧的 const 表示 pointerconst . 左侧的 const 表示指针 points to something ,即 const .

    它是 const 指针的事实意味着你不会在函数中更改 f (赋值),如果你这样做,编译器会给你一个错误 . 它没有说明函数本身 - 指向的函数在任何意义上都不是 const 因为参数是 const .

    你写的时候:

    void execute(void (const * f)(void));
    

    * 左侧的 const 表示指针指向的是 const ,而不是指针本身是 const . 因为它说指针指向那里并且你没有列出特定类型,编译器警告你类型丢失(并且默认为 int ) .

  • 0

    The const keyword should be placed between the pointer symbol (*) and the argument name (here, f):

    void execute(void (* const f)(void))
    {
      f();
    }
    

    现在,如果您尝试更改 f 的值:

    void execute(void (* const f)(void))
    {
      f = print;
      f();
    }
    

    ...您的编译器应按预期输出类似于此错误的错误:

    错误:无法使用const限定类型分配给变量'f'

相关问题