How can I get a function to call the function that called it?

I would like the next simple function to call the called function, however the function is called by several functions, so it needs to recognize which function called it, and then call it.

int wrong() { std::cout << "WRONG \n"; return 0; } 

As a continuation, is this a function that is better expressed as emptiness?

+6
source share
1 answer

What you want is a callback. Callbacks are implemented in the same way as in C ++:

 typedef int (*CallbackType)( char c ); int wrong( CallbackType callback ) { std::cout << "WRONG \n"; int r = callback( 'x' ); return r; } int also_wrong( char c ) { return wrong( also_wrong ); } 

Of course, this will lead to a fugitive recursion, so this will cause you a lot of problems, but it definitely answers your question.

And yes, if all he does is return 0 , then this is a function that will be better expressed as returning void .

+3
source

All Articles