Live data from Hacker News

Basics Of Function Pointers In C

denniskubes.com

1–10 of 61 posts

Re: Basics Of Function Pointers In C

#6
The article is missing at least one useful thing: how to declare a typedef for a function pointer. This can be used both to avoid error-prone duplication of declarations and to simplify excessively complex declarations.

Here's a simple example:

http://en.wikipedia.org/wiki/Typedef#Using_typedef_with_func...

Here's a more complex example:

http://www.devx.com/tips/Tip/13829

Here's a tutorial on how to interpret the complex declarations like the one at the top of the previous example:

http://www.codeproject.com/Articles/7042/How-to-interpret-co...

Here's a discussion about using typedefs for function pointers on StackOverflow:

http://stackoverflow.com/questions/1591361/understanding-typ...

See also: The Linux command "cdecl":

http://linux.die.net/man/1/cdecl

Plus, there's an on-line version:

http://www.lemoda.net/c/cdecl

Re: Basics Of Function Pointers In C

#9
post #7

But why that whole mess with function pointers? Where do they have the key advantage compared to directly calling the function?

If you need to determine which function to call dynamically, in an extensible way. Take a signal handler or other callback. There are more sophisticated uses, but that seems a clear and straightforward example.

Re: Basics Of Function Pointers In C

#10
post #7

But why that whole mess with function pointers? Where do they have the key advantage compared to directly calling the function?

Let's look at the signature of qsort() from libc:

   void qsort(void *base, size_t nmemb, size_t size,
           int (*compar)(const void *, const void *));
qsort is a function inside of libc.so. It's already been compiled. It doesn't know about the "compar" pointer you're going to pass it. That function might not even exist yet.

qsort doesn't know if you're sorting integers, sorting strings, sorting struct foo which is still being ironed out. It knows how to sort arrays. You give it the size of each element, the number of elements, and a function pointer that it will call to compare elements. It will call you back and you can stick your data-structure-specific knowledge into that function.

(This turns out to be a lousy way to sort arrays, by the way. If you used a C++ template instead, the comparison function could be inlined directly in the sort algorithm, which gives you better object code. But you lose the possibility that the caller and callee exist in different modules, for example.)

Post reply on HN