我想知道 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/