I have this C code that i’m having problems understanding:
int foo(int f(int,int), int g(int,int), int x) {
int y = g(x,x);
return f(y,y);
}
int sq(int x, int y) {
if (x == 1) { return y; }
return pl(y, sq(x-1, y));
}
int pl(int x, int y) {
if (x == 0) { return y; }
return pl(x-1, y+1);
}
int main (int argc, const char * argv[])
{
printf("sq = %d\n", sq);
printf("output=%d\n", foo(sq, pl, 1));
return 0;
}
I understood that f is multiplying two variables and g is multiplying, they’re apparently built in. The function foo has has two parameters declared as a function declaration -> f(int, int) and g(int, int). But then foo is passed with two arguments – sq and pl. The two arguments have also very strange values – 3392 and 3488, are those logical address of the functions sq and pl? If they are and they are passed as integers, how does foo accepts them? Since foo, has function declaration in place of the parameters where these arguments should go to.
Thank you,
EDIT: cool, thank you guys alot, that cleared things up!
fandgare not built in. They are just parameters of the functionfoo(), as you already see.Besides,
printf("sq = %d\n", sq);is undefined behaviour, assqis not an integer value, but a function resp. its address in this context. So you should writeprintf("sq = %p\n", sq);in order to cleanly output the address of the function.What really happens is that you give
foo()the functionsqas the parameterfand the functionplas the parameterg.foocalls these functions with the parameterxas written.So essentially
foocallspl(1,1)and stores the result intoywhich is then used forsq(y,y). So it delegates work to these functions. These functions can be seen as callback functions, becausefoo()calls the functions given by the caller.What
sq()andpl()do is, by now, beyond my understanding.