tags:
- c
- programming
- reddit
- social-media
- notes
source: https://www.reddit.com/r/C_Programming/comments/2tgbyr/why_function_pointers/
created: 2024-12-13
What are function pointers in C?
In C, function pointers are low-level analogs of first-class functions or closures in higher level languages.
What are some things you can implement with function pointers in C?
Some things you can implement with function pointers in C include:
- Higher-order functions.
- Dynamic dispatch.
- Parametric polymorphism.
What are two reasons why function pointers aren't widely used in C?
Two reasons why function pointers aren't widely used in C are:
/* Library */
int with_file(const char *path,
const char *mode,
void *env,
int (*func)(void *, FILE *)) {
int status;
FILE *file = fopen(path, mode);
if (!file)
return 1;
status = func(env, file);
fclose(file);
return status;
}
/* Application */
int do_something_with_file(void *env, FILE *file) {
/* ... */
}
int main(void) {
if (with_file("my_file", "r+", NULL, do_something_with_file))
return EXIT_FAILURE;
return EXIT_SUCCESS;
}
...
How as C++ first implemented?
C++ was first implemented as a preprocessor wrapped around a C compiler.
What can you use function pointers for in multithreaded C code?
In multithreaded C code, you can use function pointers as a way to provide a callback function that's called when a thread is finished.
How can function pointers be used to optimize C code?
Function pointers can be used to optimize C code by replacing conditional checks.