22 ms·
Through the title, I'm just trying to point out that function pointers are not as well-known in C as in other languages. Programmers should recognize when and h
by vickychijwani 15y ago
Through the title, I'm just trying to point out that function pointers are not as well-known in C as in other languages. Programmers should recognize when and how to use them effectively.
- Arelius 15y agoNot as well known to C programmers, or not as well known to programmers who don't program C? I don't know a single C programmer that doesn't regularly use function pointers.
- vickychijwani 15y agoBeing a student who's been in the process of learning C over the past 3 years, I for one have not come across many examples of function pointers in actual use, apart from the standard library functions qsort and bsearch.
- angersock 15y agoNo harm. :) If you want a good example of where they're useful, write the interpreter loop for a simple 3-byte wordsize VM. To expand on that, make an array of function pointers corresponding to your opcodes. Have the eval() function for a bytecode instruction use the first byte of the bytecode as the array index, and then call the function pointer at that position with the other two bytes as arguments. It's a pretty solid use case. Also, you're not strictly incorrect--the function pointer does "close over" the execution environment of the system at that time, though that's more a feature of C and globals and pointer arithmetic than anything else. ;)
- Arelius 15y agoI'm not sure that closing over only global really counts...
- angersock 15y agoYes, I suppose it doesn't, as you can't really freeze the execution state (or the relevant parts of it) for the use of the closure--e.g., somebody else can change the memory values before your code gets run and so you act on stale data. :(
- Arelius 15y agoInteresting. Function pointers are powerful, but are hardly a replacement for closures.