I have written some code for calling nested functions using callback. But i am not getting output as I expected.
Please have look into code:
#include <stdio.h>
#include <stdlib.h>
typedef int (*f_ptr)(int a, int b);
typedef int (*pair_ptr)(f_ptr);
pair_ptr cons(int a, int b)
{
int pair(f_ptr f)
{
return (f)(a, b);
}
return pair;
}
int car(pair_ptr fun)
{
int f(int a, int b)
{
return a;
}
return fun(f);
}
int main()
{
int a = 3;
int b = 4;
// It should print value of 'a'
printf("%d", car(cons(a, b))); // Error : It is printing '0'
return 0;
}
I have also tried with function pointer but in that also i am getting the same output as above.
Try this (maybe move functions and variables related to the closure to their own file):
#include <stdio.h>
typedef int (*f_ptr)(int a, int b);
typedef int (*pair_ptr)(f_ptr);
static int PairA, PairB;
static void setPairA(int a) { PairA = a; }
static void setPairB(int b) { PairB = b; }
int f(int a, int b) {
(void)b; // removed unused parameter warning
return a;
}
int pair(f_ptr fp) {
return fp(PairA, PairB);
}
pair_ptr cons(int a, int b) {
setPairA(a);
setPairB(b);
return pair;
}
int car(pair_ptr fun) {
return fun(f);
}
int main(void) {
int a = 3;
int b = 4;
printf("%d\n", car(cons(a, b)));
return 0;
}
Note that pair()
is not reentrant, nor can you call it with different values for PairA
and/or PairB
at the same time.