Just recently I have been asked in an interview: Where can we use function pointers in C?
And what function pointer returns. I said using we can call functions using function pointer then he asked some example but I could not satisfy with him some more example. He then asked me what function pointer return. I told him it depends upon the declaration of function pointers.
But I really would like to know some uses of function pointer in C.
I think the classical example in C is qsort. Quoting from there (and I DO know it’s http://www.cplusplus.com, so a not-very-good site, but it seems to be correct)
The other “classical” example is the calculator (for example see this, it’s C++ but it’s the same in C).
You have four math functions, for example
in some way you select your operation
and you can call it later (for some reason you don’t want to call it directly in the
if/switch, perhaps because you want to make other “things” that are “common” to all the operations, like logging or printing the result)Another two things you can use function pointers for are callbacks (as written by
vine'th) and “poor man” virtual functions (you put them in astructand when you create thestruct(you know, like using a “poor man” constructor, but this is C so we will call it an initializer), you save there what functions will be used by thatstruct).