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)