C中的函数指针地址运算符“不必要” [英] Function pointers in C - address operator "unnecessary"

查看:151
本文介绍了C中的函数指针地址运算符“不必要”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用qsort在C中传递一个比较函数,例如

  int cmp(const void *,const void *); 

qsort的原型需要一个int(*)(const void *,const void *)调用:

  qsort(...,cmp); 

,但它同样有效:

  qsort(...,& cmp); 

这是我们在C ++中传递静态成员函数时要做的。 Kernighan& Ritchie(2nd Edition,5.11Pointers To Functionsp119)声明由于[cmp]已知是一个函数,所以&运算符不是必需的,与在数组名称之前不需要相同。



任何人对此感到有点不舒服(尤其是关于类型安全)?

解决方案

无论你感到不舒服还是不改变C不被认为是一种类型安全的语言。例子:

  int main()
{
int integer = 0xFFFFFF;
void(* functionPointer)()=(void(*)())integer;

functionPointer();

return 0;
}

这在编译时是完全有效的,但显然不安全。 / p>

Using qsort in C we pass in a comparison function e.g.

int cmp(const void*, const void*);

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);

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)?

解决方案

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中的函数指针地址运算符“不必要”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆