c - C 中 const 限定函数的行为

标签 c function constants typedef

我想知道 const 限定函数指针是否有任何区别,因为我能想到的唯一含义是自动 const 限定其参数,当然事实并非如此。

我创建了一个小示例文件(test.c):

typedef void* vop(void*);

vop  fn;
const vop cfn;

int main(void){
    vop *p_fn = fn;
    const vop *cp_fn = fn;  // <- gives compiler warning
    vop *p_cfn = cfn;
    const vop *cp_cfn = cfn;
}

然后跑了

gcc -Wall -Wno-unused-variable -c test.c

这会产生以下警告:

warning: initialization makes '__attribute__((const))' qualified function pointer from unqualified [-Wdiscarded-qualifiers]

因此,将“指向 const vop 的指针”分配给“指向 vop 的指针”类型的变量是“可以”的,如果它不是函数指针,则会产生类似以下内容的结果:

warning: initialization discards 'const' qualifier from pointer target type [-Wdiscarded-qualifiers]

但现在它会警告相反的情况。那么问题来了:const 限定的函数指针和非 const 限定的函数指针有什么区别?


注意:cppreference有以下段落:

If a function type is declared with the const type qualifier (through the use of typedef), the behavior is undefined.

我看到的警告是“未定义行为”的结果,还是本段在这种情况下不适用(如果不适用,在什么情况下可以应用)?

最佳答案

函数类型上不能有任何类型限定符,包括 const。这样做吧undefined behavior .

摘自 C standard 的第 6.7.3p9 节:

If the specification of an array type includes any type qualifiers, the element type is so-qualified, not the array type. If the specification of a function type includes any type qualifiers, the behavior is undefined.

这声明了一个 const 函数类型:

const vop cfn;

这声明了一个指向 const 函数类型的指针:

const vop *cp_fn;

两者都违反了 6.7.3p9。

关于c - C 中 const 限定函数的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65343575/

相关文章:

c - 这段代码的输出是什么

c - 复制堆栈的算法

c++ - 有效地将多个一维数组中的数据收集到单个一维数组中

MYSQL 触发器更新未按预期工作

c++ - 何时在函数 args 中使用 const 和 const 引用?

c++ - 检测屏幕上的坐标是否可交互。

C 通过函数对 char 进行 malloc/free 双指针

无法在 if 语句内调用函数

c++ - 为什么我可以更改 const T& 参数的成员

winapi - 为什么 WSAStringToAddress 采用非常量 AddressString?