pzaenger
pzaenger

Reputation: 11973

Calling the same order of functions in C with one changing function each time. How to implement more elegantly?

I have the following code calling three different functions named func_a, func_b and func_c, which are using the same parameter. Before and after each call I need to call the functions foo and bar in order to reset/print some variables. Both are doing the same thing every time I call them.

foo();
func_a(param);
bar();

foo();
func_b(param);
bar();

foo();
func_c(param);
bar();

So, my question: is there any way to make this part more elegant? In my case it is going up to func_e, so I have five near repeats of this code.

Upvotes: 0

Views: 236

Answers (1)

jxh
jxh

Reputation: 70372

I suppose you can put all the things that are in common into a single function that invokes a function pointer. Then iterate over an array of function pointers, passing them into the single helper function:

void invoke_foo_func_bar (void (*func)(int), int param) {
    foo();
    func(param);
    bar();
}

/* ... */
void (*funcs[])(int) = { func_a, func_b, func_c };
for (int i = 0; i < sizeof(funcs)/sizeof(*funcs); ++i) {
    invoke_foo_func_bar(funcs[i], param);
}

Upvotes: 3

Related Questions