Return of functions in C

3

A very common and practical thing in interpreted languages is the return of functions from another function.

But in compiled languages as well as C , is it possible to return a function?

    
asked by anonymous 17.02.2017 / 17:45

1 answer

4

Yes, it is possible to return functions in C as in interpreted languages.

In Moon , you can declare the function you want to return, once the function returns. Ex:

function return_func()
    return function(x,y) print(x+y) end
end

But the C compiler does not have the capability to do this type of return, so you should create a pointer to the function.

void *fcn_res(){
    int sum(int x, int y){ // função que irá ser retornada
        return x+y;
    }

    void *(*res)(); // declaração genérica do ponteiro da função
    res = (void *(*)())sum;

    return (void*) res;
}

int main(){
    int (*fcn)(int, int) = fcn_res(); // atribui sum em fcn

    printf("%d\n", fcn(13,11));
    return 0;
}
    
17.02.2017 / 17:45