Why do function pointers exist?
To be clear, I understand the uses of function pointers. But as far as I know, there is no way to use actual function types in the language, so why bother with pointers? We already have syntax sugar so instead of writing
int (*fptr)(int) = &some_func;
int x = (*fptr)(5);
we write
int (*fptr)(int) = some_func;
int x = fptr(5);
Why not just use the function type directly?
int fptr(int) = some_func;
int x = fptr(5);
Posted Mar 9, 2017, 11:25 AM UTC
You're asking about the syntax of it? The problem is that:
Is perfectly valid syntax in C. The first line is a declaration to an existing function called
foothat's defined somewhere. That is not a pointer to a function, just a regular old function. Compare that with:Now we're using
fooas a pointer to a function, not a function. At the timefoois declared, the syntax would make it ambiguous as to whetherfoois a function or a pointer to a function.With the benefit of hindsight, they should have made functions values, and function declarations would then just be uninitialized function values. All that's missing is a function-value literal (lambda)
I wonder if there is a variant of C with first-class functions, not just tacked on syntax like objc blocks. It seems the delta to such a language is not very large.
If the syntax were somehow mostly backwards compatible (especially with existing programmers' minds) then that could be an interesting addition to a future version of ANSI C.
Ah, that makes sense.