Tho*_*ews 26 c function-pointers const-correctness
指针可以声明为指向可变(非常量)数据或指向常量数据的指针.
可以将指针定义为指向函数.
我的同事和我正在讨论使用带有指针的"const",并且出现了关于使用const函数指针的问题.
以下是一些问题:
typedef void (*Function_Pointer)(void); // Pointer to void function returning void.
void function_a(Function_Pointer p_func); // Example 1.
void function_b(const Function_Pointer p_func); // Example 2.
void function_c(Function_Pointer const p_func); // Example 3.
void function_d(const Function_Pointer const p_func); // Example 4.
Run Code Online (Sandbox Code Playgroud)
上述声明是将函数指针视为指向内部类型的指针的示例.
数据,变量或存储器指针允许上述组合.
所以问题是:函数指针是否具有相同的组合以及指向const函数的指针(例如示例2)是什么意思?
Jer*_*fin 47
在C中,没有函数const或其他东西,所以指向const函数的指针是没有意义的(不应该编译,虽然我没有检查过任何特定的编译器).
请注意,尽管它有所不同,但您可以拥有一个指向函数的const指针,一个指向函数返回const的指针等.基本上除了函数本身之外的所有东西都可以是const.考虑一些例子:
// 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.
Run Code Online (Sandbox Code Playgroud)
至于将指向函数的指针作为参数传递,它非常简单.您通常只想将指针传递给正确的类型.但是,指向任何类型函数的指针都可以转换为指向其他类型函数的指针,然后返回其原始类型,并保留原始值.