SLaks.Blog

Making the world a better place, one line of code at a time

Delegates vs. Function Pointers, part 1

Posted on Wednesday, June 01, 2011, at 8:21:00 PM UTC

Most languages – with the unfortunate exception of Java – allow functions to be passed around as variables.  C has function pointers, .Net has delegates, and Javascript and most functional programming languages treat functions as first class objects.

There is a fundamental difference between C-style function pointers vs. delegates or function objects.  Pure function pointers cannot hold any state other than the function itself.  In contrast, delegates and function objects do store additional state that the function can use.

To illustrate this difference,  I will use a simple example.  Most programming environments have a filter function that takes a collection and a predicate (a function that takes an item from the collection and returns a boolean), and returns a new collection with those items from the original collection that match the predicate.  In C#, this is the LINQ Where method; in Javascript, it’s the Array.filter method (introduced by Javascript 1.6).

Given a list of numbers, you can use such a method to find all numbers in the list that are greater than a local variable x.  However, in order to do that, the predicate have access to x.  In subsequent posts, I’ll explore how this can be done in different languages.

Categories: C++, C, Javascript, closures, .Net, functions Tweet this post

comments powered by Disqus