c - 指向常量函数的指针是什么意思?

标签 c function-pointers const-correctness

指针可以声明为指向可变(非常量)数据或指向常量数据的指针。
可以定义指针以指向函数。

我和我的同事正在讨论“const”和指针的使用,然后出现了关于 const 和函数指针的使用的问题。

这里有一些问题:

  1. 指向常量函数的指针与 指向非常量函数的指针?
  2. 函数可以是常量吗?
  3. 函数可以是非常量(可变的)吗?
  4. 传递函数指针的正确(安全)语法是什么?

编辑 1:函数指针语法

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.

上述声明是将函数指针视为指向内部类型的指针的示例。

数据、变量或内存指针允许上述组合。
所以问题是:函数指针可以有相同的组合吗?指向 const 函数的指针是什么意思(例如示例 2)?

最佳答案

在 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.

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

关于c - 指向常量函数的指针是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10145693/

相关文章:

c - 无法返回数组在 C 中实际上意味着什么?

c - 传递 `memset' 的 arg 2 从指针生成整数而不进行强制转换

C 结构函数指针传递自引用作为参数

iphone - NSComparisonResult 和 NSComparator - 它们是什么?

c - 如何从c中的函数指针返回类型char

c++ - 为什么我在将 ‘float**’ 转换为 ‘const float**’ 时出错?

c++ - 我在这一行代码中的语法有什么问题(指针和引用以及取消引用哦,我的)?

c++ - 使用 const_cast 添加 const 时的未定义行为?

c - C 循环中的孪生素数仅给出第一个值

c - c中正则表达式在strcmp函数中的使用