Creating an array of functions?

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
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)
I have code in all of the functions this way just to show what I'm trying to do
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
Trying
cout << (func[0])() << endl;
won't compile and assigning the function in main still returns hex value and doesn't execute the function.
Could you please show us the error(s) from your complier?
I changed the functions to int and it works but how do I get rid of return that is also printed?
> 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?
Yeah, that's why they were void first but since I can't call them without a return value I changed to int
> 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.
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.
Good to hear :)
Topic archived. No new replies allowed.