I am currently working on a project in C in which there are various function that all need become encapsulated in between two other functions. Schematically, it looks like this:
int func1(int arg) {
prepare();
doStuff();
undo();
return stuff;
}
char func2(int arg1, char* arg2) {
prepare();
doOtherStuff();
undo();
return results;
}
I've heard the preprocessor is quite powerful, so is it possible to insert the prepare()
and undo()
functions before and after the actual function body using some preprocessor mumbo-jumbo? I know that it is highly advised not to use the preprocessor if it can be avoided, yet I still am curious whether it is possible.
Cheers.
There you go:
#define MY_MACRO(doStuff) \
{ \
prepare(); \
doStuff \
undo(); \
}
Just for the record, an alternative would be to set up some form of function pointer template system:
typedef void stuff_t (void*);
void execute (stuff_t* stuff, void* result)
{
prepare();
stuff(result);
undo();
}
int func1(int arg) {
int result;
execute(do_stuff, &result);
return result;
}
char func2(int arg1, char* arg2) {
char result;
execute(doOtherStuff, &result);
return result;
}
Whether this is a good idea or not depends on what the code is actually supposed to do and what requirements there are on code re-usability.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.