Thread: Reg pointers to functions

  1. #1
    Registered User
    Join Date
    Jun 2007

    Reg pointers to functions

    Hi All,

    I'm learning Pointers to functions in C.But I have some doubts regardign the same.I would be v.happy and thankful if somebody can help me out on my pbm
    The problem is mentioned below:
    Consider I have 5 different functions which returns different type and takes different arguements also.
    Eg :
    int aaa(int x);
    void bbb(int x,int y, int z);
    void ccc(void);
    void ddd(char *x,char *y,char *z);
    void eee(UINT8 x);

    And these are all some operations when the user presses some commands,
    Commands = "command1","command2","command3","command4","comma nd5"

    How will i use the fucntion pointers to execute the corresponding function with their arguements?

    If possible, if somebody can reply to me ASAP.

    Thanks in advance,

  2. #2
    Registered Abuser
    Join Date
    Jun 2006
    Function pointers are especially handy when you want to perform a type of "overloading" in C, i.e. you may have 3 functions all defined as:
    int foo(int a, int b);
    int bar(int a, int b);
    int fred(int a, int b);
    Then you could define a function pointer:
    int (*myfunc)(int, int);
    and have a logic branch (such as a switch statement) appropriately assign the pointer depending on what command was issued:
    case CMD1: myfunc = foo; break;
    case CMD2: myfunc = bar; break;
    case CMD3: myfunc = fred; break;
    Then you could call myfunc(x, y) which will call the correct function for you. However, since all of your functions have different prototypes, I don't think function pointers will be very useful in this case. If you *really* wanted to use function pointers you could push the issue by prototyping all your functions as "void foo(void *)" and use the argument as a generic variable list. But I think in this case, since each function has its own varying set of arguments, you'd have to check the type and number of arguments anyways before trying to call the function, so you're better of with just a simple selection algorithm, i.e.:
    case CMD1: aaa(x); break;
    case CMD2: bbb(x, y, z); break;
    case CMD3: ccc(); break;
    Last edited by @nthony; 06-22-2007 at 01:10 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

    By cjohnson412 in forum C++ Programming
    Replies: 4
    Last Post: 08-11-2008, 11:48 PM
  2. Passing Structure Pointers to Functions
    By samus250 in forum C Programming
    Replies: 15
    Last Post: 03-20-2008, 04:13 PM
  3. Replies: 4
    Last Post: 11-23-2003, 07:15 AM
  4. pointers, functions, parameters
    By sballew in forum C Programming
    Replies: 3
    Last Post: 11-11-2001, 10:33 PM
Website Security Test