Thread: Functions as arguments

  1. #1
    Registered User
    Join Date
    Jan 2008
    Posts
    65

    Functions as arguments

    Is there a way to have functions as arguments? If I have a function that takes a double and returns a double, is there a way I can make another function that takes the first function as an argument?

  2. #2
    Registered User
    Join Date
    Oct 2006
    Location
    UK/Norway
    Posts
    485
    Code:
    int foo();
    
    int foofoo(int var);
    
    int main()
    {
        int a = foofoo(foo());
        return 0;
    }
    like that?

  3. #3
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Yes, for example:
    Code:
    #include <iostream>
    
    double foo(double x);
    
    void bar(double (*func)(double), double x);
    
    int main()
    {
        bar(foo, 1.5);
    }
    
    double foo(double x)
    {
        return x + x;
    }
    
    void bar(double (*func)(double), double x)
    {
        std::cout << func(x) << std::endl;
    }
    So func in bar is a function pointer, in this case a function pointer to foo. You could also use function objects instead, which can be more powerful.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 9
    Last Post: 01-26-2008, 03:12 AM
  2. NULL arguments in a shell program
    By gregulator in forum C Programming
    Replies: 4
    Last Post: 04-15-2004, 10:48 AM
  3. Passing pointers between functions
    By heygirls_uk in forum C Programming
    Replies: 5
    Last Post: 01-09-2004, 06:58 PM
  4. API "Clean Up" Functions & delete Pointers :: Winsock
    By kuphryn in forum Windows Programming
    Replies: 2
    Last Post: 05-10-2002, 06:53 PM
  5. functions and pointer arguments
    By Unregistered in forum C++ Programming
    Replies: 6
    Last Post: 01-08-2002, 05:04 PM