Functions as arguments

This is a discussion on Functions as arguments within the C++ Programming forums, part of the General Programming Boards category; Is there a way to have functions as arguments? If I have a function that takes a double and returns ...

  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
    21,589
    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.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    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, 02: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, 05: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, 04:04 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21