Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function pointers in C - address operator "unnecessary"

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

like image 789
christopherlumb Avatar asked Nov 03 '08 11:11

christopherlumb


1 Answers

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.

like image 169
Jeff Hillman Avatar answered Oct 16 '22 17:10

Jeff Hillman