Return of functions in C

Asked

Viewed 179 times

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, it is possible to return a function?

  • All programming languages or at least most have return values, in the case of C have return for all primitive types and structs except void.

1 answer

4


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

In Moon, can declare the function you want to return, already at the function return. Ex:

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

But the C compiler has no resource to make this kind of return, so it 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;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.