在C函数指针 - 地址操作员QUOT;不必要的" [英] Function pointers in C - address operator "unnecessary"
问题描述
在C使用的qsort我们传递一个比较函数例如。
Using qsort in C we pass in a comparison function e.g.
int cmp(const void*, const void*);
的qsort的protoype期望一个INT(*)(常量无效*,常量无效*),因此我们称之为:
the protoype of qsort expects a int (* )(const void* , const void*) so we call:
qsort(..., cmp);
但同样有效的调用:
but it is equally valid to call:
qsort(..., &cmp);
和这是我们必须做的,如果我们在C静态成员函数++通过。 Kernighan的&安培;里奇(第二版,5.11指向函数P119)指出,自[CMP]被称为是一个功能,和放大器;算是没有必要的,以同样的方式,它不是一个数组名称之前需要。
and this is what we would have to do if we passed in a static member-function in C++. Kernighan & Ritchie (2nd Edition, 5.11 "Pointers To Functions" p119) states that "since [cmp] is known to be a function, the & operator is not necessary, in the same way that it is not needed before an array name."
别人是否觉得这种轻微不适(尤其是对类型安全)?
Does anyone else feel slightly uncomfortable with this (esp. regarding type-safety)?
推荐答案
无论你感到不舒服与否并不能改变一个事实,即C不是认为是一种安全的语言。案例分析:</ P>
Whether you feel uncomfortable or not doesn't change the fact that C is not considered a type-safe language. Case in point:
int main()
{
int integer = 0xFFFFFF;
void (*functionPointer)() = (void(*)())integer;
functionPointer();
return 0;
}
这是在编译时完全有效的,但它显然是不安全的。
This is completely valid at compile time, but it is obviously not safe.
这篇关于在C函数指针 - 地址操作员QUOT;不必要的&QUOT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!