Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we return a function in C++?

Tags:

c++

I have a program containing three functions: main(), returnFunction() and functionToBeReturned(). main() has to call returnFunction(). Can we use functionToBeReturned() as a return value of returnFunction()?

int functionToBeReturned()
{
    // some code here....
    return value;
}

int returnFunction()
{
    // some code here....
    return functionToBeReturned();
}

int main()
{
    returnFunction();
}

Is that okay...


1 Answers

In C, you can have and return function pointers; they basically point to machine code that you can call. You might have some library functions able to "create" functions (e.g. dynamically generate or load some machine code) and give a pointer to the newly created code (dlsym, JIT libraries, ....) But, in pure standard C99 or C11 or C++11, there is no way to create raw plain functions (at the machine code level) at runtime. In a program restricted to standard C++ or C, the set of functions is fixed (and is the set of values all pointer functions can get, in addition of the NULL pointer). Since C is lacking proper closures, many C frameworks (e.g. GTK or its Glib, libevent, ....) deal with callbacks, implemented by a convention mixing function pointer and client data (for example, read the GTK tutorial, see g_signal_connect, ...)

In C++ (C++11 or newer), you can also have closures, anonymous functions (i.e. lambda-s), and std::function; for example

 std::function<int(int)> translation(int delta) {
    return [delta](int x) { return x + delta; };
 }

In the returned closure (which semantically behaves almost as a function, since you can call and apply it), the delta is a closed value.

Closures are an extremely important and difficult concept, related to lambda calculus and functional programming. Don't be surprised to need weeks to understand it. See also Scheme, Lisp In Small Pieces, SICP....

This answer to a quite similar question gives much more details.

At the machine level, a C or C++ function pointer is very often some address pointing into the code segment, but a C++ closure is some internal object (of some "anonymous" class, internal to your compiler implementation) mixing code pointers and closed values or references.

Learning some functional programming language like Ocaml or Scheme or Clojure or Haskell or Common Lisp will improve your thinking (even when coding in C or C++).

like image 178
Basile Starynkevitch Avatar answered Mar 08 '26 05:03

Basile Starynkevitch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!