|
-
Jun 10th, 2004, 08:11 PM
#1
Thread Starter
Fanatic Member
A function in C that returns a function that adds x to its argument
In a thread on JoS, Quickie asked,
"Write a function in C that returns a function that adds x to its argument."
http://discuss.fogcreek.com/joelonso...&ixPost=146457
Here's my go at it. It compiles, links, but prints junk. So it basically doesn't do what it was supposed to do. Comments welcome.
Code:
/*Write a function in C that returns a
function that adds x to its argument
x in this case is 2
*/
#include <stdio.h>
int Add2(int);
typedef int(*fnptr)(int);
int (*fn(void))(int);
int main(void)
{
int (*fnptr)(int);
fnptr=fn;
printf("%d", (*fnptr)(3));
}
int Add2(int a)
{
return a+2;
}
fnptr fn(void)
{
return &Add2;
}
-
Jun 10th, 2004, 09:01 PM
#2
see the line:
try
Also:
Code:
fnptr fn(void)
{
return &Add2;
}
Add2 is the address of the function - you dont need to take the address of it again.
Code:
fnptr fn(void)
{
return Add2;
}
Every passing hour brings the Solar System forty-three thousand miles closer to Globular Cluster M13 in Hercules -- and still there are some misfits who insist that there is no such thing as progress.
-
Jun 14th, 2004, 09:43 AM
#3
Thread Starter
Fanatic Member
Old habits die hard. Realized was calling the function fn without the paranthesis. Thanks for the awakening!
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|