Creating an array of functions?

Jul 4, 2016 at 1:41pm
I basically wanna create an array with functions for example I have:

1
2
3
  void draw0(){};
  void draw1(){};
  void draw2(){};

and I tried doing:
1
2
typedef void(*fn)();
fn func[3] = {draw0, draw1, draw2};

but when I try to output it
 
 cout << func[0] << endl;

it outputs the hex value. Any suggestions?
Last edited on Jul 4, 2016 at 1:43pm
Jul 4, 2016 at 1:45pm
Line 2: error: 'draw0' undeclared here (not in a function)
Line 2: error: 'draw1' undeclared here (not in a function)
Line 2: error: 'draw2' undeclared here (not in a function)
Jul 4, 2016 at 1:47pm
I have code in all of the functions this way just to show what I'm trying to do
Jul 4, 2016 at 1:57pm
Hi,

You didn't call the function. You may try :
cout << (func[0])() << endl;

Edit : If you don't call it, std::cout only prints the address of a function alone. If you decide to call the function, you should specify a return value for your draw functions or otherwise it won't work. std::cout cannot output void return value after all

Hope that helps.
Last edited on Jul 4, 2016 at 2:11pm
Jul 4, 2016 at 2:03pm
Trying
cout << (func[0])() << endl;
won't compile and assigning the function in main still returns hex value and doesn't execute the function.
Jul 4, 2016 at 2:08pm
Could you please show us the error(s) from your complier?
Jul 4, 2016 at 2:12pm
I changed the functions to int and it works but how do I get rid of return that is also printed?
Jul 4, 2016 at 2:16pm
> I changed the functions to int and it works but how do I get rid of return that is also printed?

What do you mean by that? You do not want cout to print the return values from your draw functions?
Jul 4, 2016 at 2:19pm
Yeah, that's why they were void first but since I can't call them without a return value I changed to int
Jul 4, 2016 at 2:28pm
> Yeah, that's why they were void first but since I can't call them without a return value I changed to int

You can simply call a function anywhere (inside or outside a cout command). Calling a func inside cout requires a return value other than void though, but I think it is safe to just remove the cout part and just call the function for good.
Jul 4, 2016 at 2:34pm
It's working now, thanks a lot. I'm making a game and I wanna add a new "frame" of a picture after every input and switching through functions seemed the easiest to do.
Jul 4, 2016 at 2:37pm
Good to hear :)
Topic archived. No new replies allowed.