且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

指向常量函数的指针的含义是什么?

更新时间:2022-04-29 04:43:46

在C语言中,不存在函数为const或其他形式的东西,因此指向const函数的指针毫无意义(尽管不能编译)我没有检查任何特定的编译器.

In C, there's no such thing as a function being const or otherwise, so a pointer to a const function is meaningless (shouldn't compile, though I haven't checked with any particular compiler).

请注意,尽管有所不同,但是您可以具有指向函数的const指针,指向返回const的函数的指针等.基本上,除了函数本身以外的所有东西都可以是const.考虑几个例子:

Note that although it's different, you can have a const pointer to a function, a pointer to function returning const, etc. Essentially everything but the function itself can be const. Consider a few examples:

// normal pointer to function
int (*func)(int);

// pointer to const function -- not allowed
int (const *func)(int);

// const pointer to function. Allowed, must be initialized.          
int (*const func)(int) = some_func;

// Bonus: pointer to function returning pointer to const
void const *(*func)(int);

// triple bonus: const pointer to function returning pointer to const.
void const *(*const func)(int) = func.

就将指针作为参数传递给函数而言,这非常简单.通常,您只希望将指针传递给正确的类型.但是,指向任何类型的函数的指针都可以转换为指向其他某种类型的函数的指针,然后返回其原始类型,并保留原始值.

As far as passing a pointer to a function as a parameter goes, it's pretty simple. You normally want to just pass a pointer to the correct type. However, a pointer to any type of function can be converted to a pointer to some other type of function, then back to its original type, and retain the original value.