Friday, February 27, 2009

Subroutine Pointer in C

C has subroutine pointers. It does not require closures because it does not have nested scopes and it is static scoped. Every subroutine is at global scope. As a result, the referencing environment for a subroutine is the same whether it is created when the subroutine is first passed a parameter or when the subroutine is finally called. In the following code, plus_one has the same referencing environment whether the referencing environment is created when it is passed as a parameter to caller or when it is called in caller.

#include
int plus_one(int n) {
return n + 1;
}
void caller(int (*f) (int)) {
int result = f(3);
printf("3 plus 1 is %d\n", result);
}
int main() {
caller(plus_one);
return 0;
}

For a language which supports nested scope, the situation is different. In the following Common Lisp code, a closure must be created for plus_2 to make it a function which addes 2 to its sole parameter.

(let ((one 1))
(defun plus_1 (x)
(+ x one)))

(let ((one 5))
(plus_1 3))

No comments: