Array of functions

This is a discussion on Array of functions within the C Programming forums, part of the General Programming Boards category; Hello everybody. While I was looking for a way to call different functions knowing a number related to the function, ...

  1. #1
    Registered User
    Join Date
    Jun 2010
    Posts
    182

    Array of functions

    Hello everybody.

    While I was looking for a way to call different functions knowing a number
    related to the function, I mean n = 1 relates to function() number 1, n = 2 relates to
    function() number 2, and so on, I found this article, that is talking about this stuff
    but for C++.

    Do you know if it can be done in C as well? What would be different between C and C++?

    Thanks

    Code:
    Array of Functions
    Labels: Arrays, Functions, Miscellaneous, Pointers
    
    In the article Pointers to Function, we saw how pointers can be made
    to point at functions and hence can be used to invoke them.
    
    By far the most important use of pointers to functions is to have arrays of functions. 
    This can be achieved as stated below
    
    You already know that we can have arrays of pointers and pointers 
    can be made to point at functions. 
    So combining both we can have array of pointers to functions put differently, 
    we can have array of functions.
    
    The example program below demonstrates how we can have array of functions; 
    please note that this concept is mostly used in writing compilers and interpreters,
    so you shouldn’t expect the program to do anything serious or useful!
    
      // Program to demonstrate
      // array of functions
      #include<iostream.h>
    
      // -- FUNCTION PROTOTYPES --
      void func1();
      void func2();
      void func3();
      void func4();
      void func5();
      // -- ENDS --
    
      void main()
      {
       // notice the prototype
       void (*ptr[5])();
    
       // arrays are made to point
       // at the respective functions
       ptr[0]=func1;
       ptr[1]=func2;
       ptr[2]=func3;
       ptr[3]=func4;
       ptr[4]=func5;
    
       // now the array elements
       // point to different functions
       // which are called just like
       // we access the elements of
       // an array
       for(int i=0;i<5;i++)
         (*ptr[i])();
      }
    
      // -- FUNCTIONS DEFINITION --
      void func1()
      {
       cout<<"Called Func1!\n";
      }
    
      void func2()
      {
       cout<<"Called Func2!\n";
      }
    
      void func3()
      {
       cout<<"Called Func3!\n";
      }
    
      void func4()
      {
       cout<<"Called Func4!\n";
      }
    
      void func5()
      {
       cout<<"Called Func5!\n";
      }
      // -- ENDS --
    Last edited by frktons; 06-29-2010 at 05:32 PM.

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Replace all of the cout lines, and try it. Yes, there are function pointers in C.


    Quzah.
    Hope is the first step on the road to disappointment.

  3. #3
    Registered User
    Join Date
    Jun 2010
    Posts
    182
    Quote Originally Posted by quzah View Post
    Replace all of the cout lines, and try it. Yes, there are function pointers in C.


    Quzah.
    And what about:

    Code:
    #include<iostream.h>
    I have no header with this name in my C compiler.
    Maybe
    Code:
    #include <stdio.h>
    is the substitute?

    Thanks

  4. #4
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Yes, of course!

    You can't be afraid to just try these idea's - consider that it took you many times longer to post your question, than it would have taken you to just try it.

    And that doesn't take into account your time lost while you wait around for an answer.

    Learning programming implies, indeed requires, some experimentation on your part.

  5. #5
    Registered User
    Join Date
    Jun 2010
    Posts
    182
    Quote Originally Posted by Adak View Post
    Yes, of course!

    You can't be afraid to just try these idea's - consider that it took you many times longer to post your question, than it would have taken you to just try it.

    And that doesn't take into account your time lost while you wait around for an answer.

    Learning programming implies, indeed requires, some experimentation on your part.
    Thanks Adak.

    Well, I'm not afraid to try my ideas, I just enjoy more to interact with people. :-)

    Time doesn't matter when you enjoy. I could search a million web sites and find all the
    answers I need, and the code, and everything else. But it would be less fun :-(

    To be honest I'm not learning programming, I'm just learning C. It is quite different.

    Enjoy

  6. #6
    Registered User
    Join Date
    Jun 2010
    Posts
    9
    Code:
    #include <stdio.h>
    
    void func1() {	printf("Function 1 Called\n"); }
    void func2() {	printf("Function 2 Called\n"); }
    void func3() {	printf("Function 3 Called\n"); }
    
    int main(int argc, char *argv[])
    {
    	static void (*ptr[3])() = {func1,func2,func3};
    	int k=0;
    	for(k=0;k<3;k++)
    		ptr[k]();
    	return 0;
    }
    illustrates the C equivalent of how to arrange an array of function pointers.

  7. #7
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,635
    Note that the example uses void main, but you should not.
    Also might be my preference, but I always put & before functions when taking their addresses. Not required, but since since you have to do it for variables, why not functions?
    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.

  8. #8
    Registered User
    Join Date
    Jun 2010
    Posts
    182

    Thumbs up

    Quote Originally Posted by Scramble View Post
    Code:
    #include <stdio.h>
    
    void func1() {	printf("Function 1 Called\n"); }
    void func2() {	printf("Function 2 Called\n"); }
    void func3() {	printf("Function 3 Called\n"); }
    
    int main(int argc, char *argv[])
    {
    	static void (*ptr[3])() = {func1,func2,func3};
    	int k=0;
    	for(k=0;k<3;k++)
    		ptr[k]();
    	return 0;
    }
    illustrates the C equivalent of how to arrange an array of function pointers.
    Thanks, very useful.

    Quote Originally Posted by Elysia View Post
    Note that the example uses void main, but you should not.
    Also might be my preference, but I always put & before functions when taking their addresses. Not required, but since since you have to do it for variables, why not functions?
    You are right, indeed. I just copied the article, I'm not going to use void main() . :-)

    Something interesting is one sentence of the article I posted:
    Code:
    please note that this concept is mostly used in writing compilers and interpreters
    As a matter of fact the use I'm thinking about this function addressing is something
    similar to an interpreter. ;-)

    Using your suggestions, I modified the routine, and now it works in C:
    Code:
      // Program to demonstrate
      // array of functions
      #include<stdio.h>
    
      // -- FUNCTION PROTOTYPES --
    
      void func1(void);
      void func2(void);
      void func3(void);
      void func4(void);
      void func5(void);
      // -- ENDS --
    
      int main(void)
      {
       // notice the prototype
    
       void (*ptr[5])();
    
       // arrays are made to point
       // at the respective functions
    
       ptr[0]=&func1;
       ptr[1]=&func2;
       ptr[2]=&func3;
       ptr[3]=&func4;
       ptr[4]=&func5;
    
       // now the array elements
       // point to different functions
       // which are called just like
       // we access the elements of
       // an array
    
       for(int i=0;i<5;i++)
         ptr[i]();
       return 0;
      }
    
      // -- FUNCTIONS DEFINITION --
    
      void func1(void)
      {
       printf("Called Func1!\n");
      }
    
      void func2(void)
      {
       printf("Called Func2!\n");
      }
    
      void func3(void)
      {
       printf("Called Func3!\n");
      }
    
      void func4(void)
      {
       printf("Called Func4!\n");
      }
    
      void func5(void)
      {
       printf("Called Func5!\n");
      }
    and the output:
    Code:
    Called Func1!
    Called Func2!
    Called Func3!
    Called Func4!
    Called Func5!
    Press any key to continue...
    Thanks everybody
    Last edited by frktons; 06-30-2010 at 08:02 AM.

  9. #9
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,635
    You may also want to know of a trick to simplify the code.
    Function pointer declarations are horrible, and even more so if you're going to return them from a function. Thankfully, we can abstract this by creating a type alias:

    typedef void (FncPtr_t)();
    FncPtr_t* ptr[5];

    Looks much better, don't you think?
    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.

  10. #10
    Registered User
    Join Date
    Jun 2010
    Posts
    182
    Quote Originally Posted by Elysia View Post
    You may also want to know of a trick to simplify the code.
    Function pointer declarations are horrible, and even more so if you're going to return them from a function. Thankfully, we can abstract this by creating a type alias:

    typedef void (FncPtr_t)();
    FncPtr_t* ptr[5];

    Looks much better, don't you think?
    Good, I'll consider this option as well, thanks.

    Now let's move one step further. What if I'd like to declare an array of functions
    each taking 2 char parameters? Can anyone show me some implementation of this?

    Would it be something like:

    Code:
    typedef void (FncPtr_t)(char, char);
    FncPtr_t* ptr[5];
    or what?

    Thanks

  11. #11
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,635
    Yes, that's correct.
    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.

  12. #12
    Registered User
    Join Date
    Jun 2010
    Posts
    182

    Array of functions

    OK.

    Now I've tried to implement the parameters, based on the previous version.
    Next I'll try the version proposed by Elysia.
    Code:
      // Program to demonstrate
      // array of functions
      #include<stdio.h>
    
      // -- FUNCTION PROTOTYPES --
    
      void func1(char, char);
      void func2(char, char);
      void func3(char, char);
      void func4(char, char);
      void func5(char, char);
      // -- ENDS --
    
      int main(void)
      {
       // notice the prototype
    
       void (*ptr[5])(char, char);
    
       // arrays are made to point
       // at the respective functions
    
       ptr[0]=&func1;
       ptr[1]=&func2;
       ptr[2]=&func3;
       ptr[3]=&func4;
       ptr[4]=&func5;
    
       // now the array elements
       // point to different functions
       // which are called just like
       // we access the elements of
       // an array
    
       for(int i=0;i<5;i++)
         ptr[i]('A',' ');
       return 0;
      }
    
      // -- FUNCTIONS DEFINITION --
    
      void func1(char token, char times)
      {
       printf("Called Func1!\n");
       printf("Token = \'%c\' - to repeat %d times\n",token,times);
      }
    
      void func2(char token, char times)
      {
       printf("Called Func2!\n");
       printf("Token = \'%c\' - to repeat %d times incremented by 1\n",token,times);
      }
    
      void func3(char token, char times)
      {
       printf("Called Func3!\n");
       printf("Token = \'%c\' - to repeat %d times doubled\n",token,times);
      }
    
      void func4(char token, char times )
      {
       printf("Called Func4!\n");
       printf("Token = \'%c\' - to repeat %d times doubled except the last time\n",token,times);
      }
    
      void func5(char token, char times)
      {
       printf("Called Func5!\n");
       printf("Token = \'%c\' - to repeat %d times tripled\n",token,times);
      }
    and the output:
    Code:
    Called Func1!
    Token = 'A' - to repeat 32 times
    Called Func2!
    Token = 'A' - to repeat 32 times incremented by 1
    Called Func3!
    Token = 'A' - to repeat 32 times doubled
    Called Func4!
    Token = 'A' - to repeat 32 times doubled except the last time
    Called Func5!
    Token = 'A' - to repeat 32 times tripled
    Press any key to continue...

  13. #13
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,635
    You are printing a char with %d. This is obviously a bad idea™.
    Either you pass an int or you cast the char to an int before passing it to printf.
    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.

  14. #14
    Registered User
    Join Date
    Jun 2010
    Posts
    182
    Quote Originally Posted by Elysia View Post
    You are printing a char with %d. This is obviously a bad idea™.
    Either you pass an int or you cast the char to an int before passing it to printf.
    According to what I've read, chars have a double nature, and can
    be used in both ways. What are your comments related to? I
    mean what risk you are pointing to?

  15. #15
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,635
    Yes, they can be used in many ways. It is a storage of 1 byte, but it's usually used to represent characters.
    But that's not the problem. You can safely pass <= 255 to it, but you are lying to printf by saying you are passing an int:
    printf("Token = \'%c\' - to repeat %d times tripled\n",token,times);
    Either you pass an int from the beginning:
    Code:
      void func5(char token, int times)
    {
        printf("Called Func5!\n");
        printf("Token = \'%c\' - to repeat %d times tripled\n",token,times);
    }
    Or you cast the char to an int:
    Code:
      void func5(char token, char times)
    {
        printf("Called Func5!\n");
        printf("Token = \'%c\' - to repeat %d times tripled\n",token,(int)times);
    }
    The format specifier is there to tell printf what types you are passing to it, so you can obviously not lie. That will cause undefined behavior.
    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.

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Array of Functions?
    By CPlus in forum C++ Programming
    Replies: 10
    Last Post: 05-10-2010, 02:06 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. Unknown Memory Leak in Init() Function
    By CodeHacker in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2004, 09:54 AM
  4. Merge sort please
    By vasanth in forum C Programming
    Replies: 2
    Last Post: 11-09-2003, 11:09 AM
  5. Array Program
    By emmx in forum C Programming
    Replies: 3
    Last Post: 08-31-2003, 12:44 AM

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