Reputation: 31
The return value of the function "fun" is unexpected
I'm learning C by writing a high order function "funfun" to return a function "fun"
#include<stdio.h>
void* funfun(const int k) {
int fun(const int c) {
//int sum = k + c;
printf("k = %d, c = %d, sum = %d\n", k, c, k + c);
return k + c;
}
return fun;
}
int main() {
int (*ptr)(int) = funfun(3);
printf("%d\n", ptr(2));
return 0;
}
Commenting out "int sum = k + c;", the display is unexpected:
k = 3, c = 2, sum = 5
134513986
Keeping that line, the display is expected:
k = 3, c = 2, sum = 5
5
The code is compiled and executed with:
gcc a.c -o a && ./a
gcc -v shows:
gcc version 4.1.2 20080704 (Red Hat 4.1.2-50)
Upvotes: 3
Views: 49
Reputation: 206689
You are using a GCC extension called Nested Functions.
In that documentation, you can discover that what you are doing is not allowed:
But this technique works only so long as the containing function (hack, in this example) does not exit.
The "containing function" is funfun
in your case.
If you try to call the nested function through its address after the containing function exits, all hell breaks loose.
C does not really have higher-order functions (with closures etc.). This extension to C doesn't really provide those either.
Upvotes: 2