Ran across this cryptic code for C, I got blown away

G

G Patel

Hello,

I ran across the following code, and it blew me away (I've been
programming in C for 3 months now). I've checked tutorials, books,
etc., but I can't find any idioms such as below. Can someone help me
decipher it ?

#include <stdio.h>

typedef int (* f_p)(int); /* 1: what does this do? */
static int k = 0;

int add (int x) { return k + x; } ; /* 2: what is this? ending with ;
? */

f_p addn(int n)
{
k = n;
return add ; /* 3: what is all this? Return value? */
}

int main ( int argv, char** argc ) {

printf("Calling (*addn(12))(13): %d\n",
(addn(12))(13));
printf("Calling (*addn(1))(13): %d\n",
(addn(1))(13));
printf("Calling (*addn(2))(3): %d\n",
(addn(2))(3));

return 0;
}

===

I have a feeling addn returns a pointer that was defined in typedef.
I've never seen such a thing before, but it seems like such a return
value is hard to show in the actual function header so the typedef is
used. As for the rest, I am totally lost.

Thx
 
A

Artie Gold

G said:
Hello,

I ran across the following code, and it blew me away (I've been
programming in C for 3 months now). I've checked tutorials, books,
etc., but I can't find any idioms such as below. Can someone help me
decipher it ?

#include <stdio.h>

typedef int (* f_p)(int); /* 1: what does this do? */

It says that `f_p' is a synonym for the type: "a pointer to a function
that takes an `int' as an argument and returns an `int'.
static int k = 0;

int add (int x) { return k + x; } ; /* 2: what is this? ending with ;
? */
It's a stray `;' (an empty statement).
f_p addn(int n)
{
k = n;
return add ; /* 3: what is all this? Return value? */
Yes. It is returning a pointer to the function `add', after setting the
static int `k' to the desired value.

The return type is `f_p', as explained above.
int main ( int argv, char** argc ) {

printf("Calling (*addn(12))(13): %d\n",
(addn(12))(13));
printf("Calling (*addn(1))(13): %d\n",
(addn(1))(13));
printf("Calling (*addn(2))(3): %d\n",
(addn(2))(3));

return 0;
}

===

I have a feeling addn returns a pointer that was defined in typedef.
I've never seen such a thing before, but it seems like such a return
value is hard to show in the actual function header so the typedef is
used. As for the rest, I am totally lost.
It's just a fragile fake closure.

HTH,
--ag
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top