Can we return a function in C++? -


i have program containing 3 functions: main(), returnfunction() , functiontobereturned(). main() has call returnfunction(). can use functiontobereturned() return value of returnfunction()?

int functiontobereturned() {     // code here....     return value; }  int returnfunction() {     // code here....     return functiontobereturned(); }  int main() {     returnfunction(); } 

is okay...

in c, can have , return function pointers; point machine code can call. might have library functions able "create" functions (e.g. dynamically generate or load machine code) , give pointer newly created code (dlsym, jit libraries, ....) but, in pure standard c99 or c11 or c++11, there no way create raw plain functions (at machine code level) @ runtime. in program restricted standard c++ or c, set of functions fixed (and set of values pointer functions can get, in addition of null pointer). since c lacking proper closures, many c frameworks (e.g. gtk or glib, libevent, ....) deal callbacks, implemented convention mixing function pointer , client data (for example, read gtk tutorial, see g_signal_connect, ...)

in c++ (c++11 or newer), can have closures, anonymous functions (i.e. lambda-s), , std::function; example

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

in returned closure (which semantically behaves function, since can call , apply it), delta closed value.

closures extremely important , difficult concept, related lambda calculus , functional programming. don't surprised need weeks understand it. see scheme, lisp in small pieces, sicp....

this answer quite similar question gives more details.

at machine level, c or c++ function pointer address pointing code segment, c++ closure internal object (of "anonymous" class, internal compiler implementation) mixing code pointers , closed values or references.

learning functional programming language ocaml or scheme or clojure or haskell or common lisp improve thinking (even when coding in c or c++).


Comments