Robert Moore Robert Moore - 2 months ago 6
C Question

Concatenate two functions into one in C

How can I concatenate (or merge) two functions that take no arguments and return nothing into one function? In JavaScript I would do this:

function f1() {
console.log("f1 called");
}
function f2() {
console.log("f2 called");
}
function function_concat(fa, fb) {
var final = function() {
fa();
fb();
};
return final;
}
var merged = function_concat(fa, fb);
merged();


In C, this is what I have:

#include <stdio.h>
#include <stdlib.h>

typedef void (*fptr)(void);
void f1() {
printf("f1 called");
}
void f2() {
printf("f2 called");
}

fptr function_concat(fa, fb) {
// What to do here??
}
int main(int argc, const char **argv) {
fptr merged = function_concat(f1, f2);
fptr();
}


I know I'll have to return a static pointer, but I can't define a function in a function in C which makes it hard to create new functions if I'm already in a function. Does anybody know a way to do this?

Answer

You can't define function at runtime in C, so you're only option is to implement some sort of proxy. You can use global variables to refer to the function pointers, but to give an implicit answer, you can't really emulate this in C.

If you ever need to change the interface of fa_ and fb_ you'll need to call function_concat again, or set the global variables directly, but at that point you wouldn't need the proxy function.

static fptr fa_, fb_;

void function_concat_proxy() {
    fa_();
    fb_();
}

fptr function_concat(fptr fa, fptr fb) {
    fa_ = fp;
    fb_ = fb;
    return function_concat_proxy;
}
Comments