Returning function as the result of a subroutine

In the C language, function are not firt-class objects, “a first-class object (also value, entity, and citizen), in the context of a particular programming language, is an entity that can be constructed at run-time, passed as a parameter, returned from a subroutine, or assigned into a variable”.wikipedia – http://en.wikipedia.org/wiki/First-class_object. However, given that pointer are first-class object , the we can to associate pointer to functions, simulating “first-class function”. Passign functions as a parameter to a subroutine is usual, there are several functions int the standard libray, like bsearch (http://www.cplusplus.com/reference/clibrary/cstdlib/bsearch/). However, we can return pointer to functions as the result of a subroutine:

typedef int (*intint)(int); 
intint addk (int k){ 
 int f (int n){ k = k+1; return n + k; } 
 return f; 
} 

After that , we can use it in our programs, for example:

intint f = addk(10); 
printf ("%d\n", f(4)); // 14 
printf ("%d\n", f(4)); // 15 
Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s