Results 1 to 3 of 3

Thread: A function in C that returns a function that adds x to its argument

  1. #1

    Thread Starter
    Fanatic Member
    Join Date
    Feb 2003
    Location
    C:\Windows\Microsoft.NET\Framework
    Posts
    574

    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;
    }

  2. #2
    PowerPoster sunburnt's Avatar
    Join Date
    Feb 2001
    Location
    Boulder, Colorado
    Posts
    1,403
    see the line:

    Code:
    fnptr=fn;
    try

    Code:
    fnptr=fn();
    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.

  3. #3

    Thread Starter
    Fanatic Member
    Join Date
    Feb 2003
    Location
    C:\Windows\Microsoft.NET\Framework
    Posts
    574
    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
  •  



Click Here to Expand Forum to Full Width