Array of Functions?

This is a discussion on Array of Functions? within the C++ Programming forums, part of the General Programming Boards category; Hello I was just wondering if it was possible to make an array of functions? To roughly get an idea, ...

  1. #1
    Registered User
    Join Date
    Feb 2010
    Posts
    67

    Smile Array of Functions?

    Hello

    I was just wondering if it was possible to make an array of functions?
    To roughly get an idea, here is some fake code:

    Code:
    int function[2]; //the array would be called 'function', have 2 slots, with the functions being int types
    
    function[0](x) //the first function would take on the name function[0] and take one argument
    {
        cout << x << endl;
    }
    
    function[1](y) //the second function would have name function[1] and have one arg
    {
        cout << y*y << endl;
    }
    
    int main()
    {
        function[0](1); //x = 1 as an example
        function[1](2); //y = 2 as an example
    }
    In this case the output of the program would be
    1
    4

    This is fake code that does not work. I was just curious if there was a way to do such a thing.

    The advantage I'm looking for is to have indexed names for functions, which would make them easier to organize.

    How is this done in C++?

    Thanks everyone

  2. #2
    Registered User
    Join Date
    Aug 2005
    Posts
    266
    sort of, make an array of void pointers

    ive never had use for it since for some reason I dont do real programming but I think its something like this...

    Code:
    int hey()
    {return 0;}
    
    int bye()
    {return 0;}
    
    int main()
    {
    void * myfuncs[10];
    myfuncs[0] = &hey;
    myfuncs[1] = &bye;
    }
    im sure someone here can correct this , its likely not right.
    Last edited by rodrigorules; 05-08-2010 at 05:00 PM.

  3. #3
    The larch
    Join Date
    May 2006
    Posts
    3,573
    Yes, it is possible with function pointers.

    Code:
    #include <iostream>
    using namespace std;
    
    void  foo(int x)
    {
        cout << x << endl;
    }
    
    void bar(int y)
    {
        cout << y*y << endl;
    }
    
    typedef void (*func)(int);  //use a typedef to keep your sanity
    
    func functions[] = {foo, bar};
    
    int main()
    {
        functions[0](1); //x = 1 as an example
        functions[1](2); //y = 2 as an example
    }
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

  4. #4
    Webhead Spidey's Avatar
    Join Date
    Jul 2009
    Posts
    285
    You an make an array of function pointers, each pointing to a function of a similar signature. eg

    Code:
    typedef void (*voidFunc) (void);
    
    void f0();
    void f1();
    ...
    void f9();
    
    voidFunc funcArray[10];
    
    funcArray[0] = f0;
    funcArray[1] = f1;
    ...
    funcArray[9] = f9;
    
    //call functions
    for(int i = 0; i < 10; ++i)
      funcArray[i]();
    Spidey out!

  5. #5
    Registered User
    Join Date
    Feb 2010
    Posts
    67
    I'm sure you pros know the benefits of being able to organize functions this way all too well. Thanks.

  6. #6
    Registered User
    Join Date
    May 2009
    Posts
    242
    typedef void (*func)(int);
    that's a new syntax for me for typedef, so i'll try to paraphrase what it means in order to get a better grasp: When you make this statement, you declare func to be an alias for the datatype "pointer to a function that takes an integer argument and has return type void".

    So, in anon's code, one should after that also be able to write something like this in main(), right (?):
    Code:
    func ptr;
    ptr = foo;
    ptr(2); // same as foo(2);
    ptr = bar;
    ptr(2); // same as bar(2);
    ...
    also, (if we don't mind losing our sanity) would there be a way to do this at all without the typedef?

  7. #7
    Registered User
    Join Date
    Jun 2005
    Posts
    6,210
    Quote Originally Posted by Aisthesis View Post
    also, (if we don't mind losing our sanity) would there be a way to do this at all without the typedef?
    Sure.
    Code:
    void (*ptr)(int);
    ptr = foo;
    ptr(2); // same as foo(2);
    ptr = bar;
    ptr(2); // same as bar(2);
    If you want to declare an array of such pointers, the approach is
    Code:
    void (*array[2])(int);
    array[0] = foo;
    array[0](2); // same as foo(2);
    array[0] = bar;
    array[0](2); // same as bar(2);
    Due to potential to put things in the wrong place (eg brackets, array dimensions) a typedef helper is usually the way to go. But techniques like the above can be a little useful in code obfuscation contests
    Right 98% of the time, and don't care about the other 3%.

  8. #8
    Registered User
    Join Date
    Mar 2010
    Posts
    68

    little more

    The above code might be incorrect, I don't feel like testing it out. So, if it works great, stop reading, but I believe the correct way is below.

    Code:
    typedef void (*func) ();// notice how you are storing a POINTER??? if you store an array of pointers, you CANNOT simply use the index operator to call the function because that merely fetches the pointer.
    
    void f(){ }// does nothing
    
    
    func funcArray[10] ;
    
    funcArray[0] = f;
    
    (*funcArray[0])();// parenthesis are needed

    // in order to call the function stored in the first position of the array, you have to deference it twice, not once, although maybe some compilers might figure it out? I am not sure, but here is why. Functions are really pointers, so when you store a function in the array, you have to deference twice to call the function, make sense?
    Last edited by smasherprog; 05-09-2010 at 11:56 PM.

  9. #9
    Registered User
    Join Date
    Oct 2006
    Posts
    2,305
    another option might be an array of functors (class objects that implement the () operator). you could have an array or an std::vector of base objects that all of your functor classes derive from, and based on the type of object, determined by RTTI or some other method, you can determine the parameters it takes.

  10. #10
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,457
    Not that you'll be needing it for this, but if you're into functors and stuff, you might find boost::bind useful. Just a tip.
    Oh yes, and C++0x supports lambdas, enabling you to create functions "inline", and the auto keyword allows you store variables with these functions. So essentially, you are storing functions in a variable. Although the exact type and implementations details are probably unknown to us.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  11. #11
    Registered User whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    7,638
    Quote Originally Posted by smasherprog View Post
    The above code might be incorrect, I don't feel like testing it out. So, if it works great, stop reading, but I believe the correct way is below.
    Be sure next time. The difference is that grumpy did not use a typedef, per another member's request. His code and yours should work.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Code review
    By bennywhere in forum C Programming
    Replies: 16
    Last Post: 10-20-2009, 09:00 PM
  2. warning: excess elements in array initializer
    By redruby147 in forum C Programming
    Replies: 6
    Last Post: 09-30-2009, 06:08 AM
  3. Merge sort please
    By vasanth in forum C Programming
    Replies: 2
    Last Post: 11-09-2003, 11:09 AM
  4. Struct *** initialization
    By Saravanan in forum C Programming
    Replies: 20
    Last Post: 10-09-2003, 12:04 PM
  5. Creating 2D arrays on heap
    By sundeeptuteja in forum C++ Programming
    Replies: 6
    Last Post: 08-16-2002, 11:44 AM

Tags for this Thread


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