C++, How to make function run another function, eg void func(void func2)

Started by
19 comments, last by wild_pointer 19 years, 6 months ago
Hi, I want to run a function from a function. eg.

//init
void init(void run)  {
    run();
}

//and being used...
void run() {
}

int main() {
    init(run());
    return 0;
}

thanks
Advertisement
function pointers
Lucas Henekswww.ionforge.com
You have a problem. Functions can take values as parameters, but void is not a value type (except void *). Furthermore, functions are not values, so you can't pass them - at least, not directly.

Solution? Use a function pointer.

[Edit: source snippet removed.]
Ok, I made my function ok, eg void run(void func()){func();}

But is it possible to store it in a global variable.

eg. something like so:
void globalFunc();void doBeep() { Beep(33,33);}int main() {     globalFunc = doBeep;      globalFunc(); //goes beep     return 0;}


ok, first, it's:
void run(void (*func)()){func();}
not:
void run(void func()){func();}

and to answer your question, the way you make a function pointer is
void (*func)();
Quote:Original post by Roboguy
ok, first, it's:
void run(void (*func)()){func();}
not:
void run(void func()){func();}

and to answer your question, the way you make a function pointer is
void (*func)();


Thanks it works, but out of curiosity i was wondering what the difference between:
void run(void (*func)()) {     func();}//andvoid run(void func()) {     func();}

is?


And when I'm using the global function pointer, eg
void (*func)();void doBeep() {	Beep(200,50);}void run(void (*func)()) {     func();}int WINAPI WinMain( HINSTANCE hInst, HINSTANCE, LPSTR, INT ){	func = doBeep; //do i do this or        func = &doBeep; // as they both work.	        run(func);	return 0;}
One can't pass a function by value, it needs to be a function pointer [though the [std?] notation would suggest otherwise].
1) The second one doesn't work
2) func = doBeep;
func = &doBeep fits better with standard notation, but func = doBeep seems to be standard aswell, so why not?
"1) The second one doesn't work"

Nope, that works perfectly. It's a completely valid syntax.

This topic is closed to new replies.

Advertisement