2 ms·
> You can pass functions but not return them. #include <stdio.h> char *f(void) { return "Yes, you can..."; } char *(*g(void))(void) { return
by jolmg 7y ago
> You can pass functions but not return them.
#include <stdio.h>
char *f(void) {
return "Yes, you can...";
}
char *(*g(void))(void) {
return f;
}
int main() {
puts(g()());
return 0;
}
- User23 7y agoTechnically passing and returning function pointers is very different from passing and returning functions. This has implications for things like closures.
- jolmg 7y agoBy the fact that lmm said "You can pass functions", they probably meant "function pointers", since that's the only way you can pass in something that could be referred to as a function in C. EDIT: At least last I heard. The example I gave is C89, and I know C99 and some GNU extensions. I don't know if a new standard introduced something else that could be referred to as a function that can be passed in but not returned. A quick google for "c lambda" and "c closure" as well as looking for those keywords in the Wikipedia articles of C11 and C18 turned up nothing, so I guess not.
- earenndil 7y agoGNU c can have lambda expressions[1]. And clang does even have closures[2]. 1: http://walfield.org/blog/2010/08/25/lambdas-in-c.html http://walfield.org/blog/2010/08/25/lambdas-in-c.html 2: https://en.wikipedia.org/wiki/Blocks_(C_language_extension) https://en.wikipedia.org/wiki/Blocks_(C_language_extension)
- saagarjha 7y agoNote that the first example relies on multiple GCC-only features, one of which is the atrocity that is nested functions, and even then technically invokes undefined behavior.
- kazinator 7y agoGNU C has "downward funarg" closures, like Pascal. They have the same representation as function pointers, which requires the compiled code to generate trampolines (little pieces of machine code that find a PC-relative environment pointer) on the stack. Invoking them requires executable stacks (a linker-level executable option often now turned off by default in major GNU/Linux distros).