Question

I have a bunch of functions that all start and end the same way with only the middle part being different.

I know I could do:

int
foo(int bar)
{
    intro();
    /* stuff that differs */
    outro();
}

but I was wondering if there is another way, saving me from retyping the intro() and outro() in all functions.

Was it helpful?

Solution 2

First, you should read about Aspect Oriented Programming. It's relevant to your query.

Second, you should be happy with whatever method lets you avoid code duplication. What you showed has nothing obviously wrong with it.

OTHER TIPS

One way is to use function pointers. void (*function)(void) is a pointer to a function that returns void and takes no parameters.

int foo(int bar, void (*function)(void))
{
    intro();
    /* call the function*/
    function();
    outro();
}

You call this by passing the address of a function that has the prototype

void someFunctionName(void).

Adjust to taste if the "stuff that differs" ought to take arguments or return a value.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top